오늘은 알고리즘 문제풀이 가이드 세션이 있었다. 이 과정으로 처음 프로그래밍을 접하는 사람들도 많기 때문에 주로 입문에 맞춘 설명이었다. 같이 간단한 예제를 풀어보고 설명해주고, 알고리즘 풀이에 대한 접근을 제시해주었다. 그리고 이 과정이 끝날 때 백준 골드, 프로그래머스 3단계는 되어야 한다고 했다. 프로젝트 진행하며 PS를 병행하기 쉽지 않겠지만 둘 다 챙겨야지 어쩌겠나.
코틀린 문법 강의가 진행중이다. 기초부터 클래스, 쓰레드, 코루틴까지 다루게 된다. 그 중 메서드 부분을 공부하다가 함수의 기본 반환형이 Unit임을 보고 Unit이 뭔지 찾아보았다.
함수의 반환값이 없으면 반환 기본값은 Unit 이다. 이건 void에 해당한다. 왜 코틀린은 void 대신 Unit 클래스를 만들어 쓰는 걸까? 이걸 알기 위해서는 먼저 Any를 알아야 한다.
In Kotlin, everything is an object in the sense that you can call member functions and properties on any variable. While certain types have an optimized internal representation as primitive values at runtime (such as numbers, characters, booleans and others), they appear and behave like regular classes to you.
The basic types used in Kotlin:
- Numbers and their unsigned counterparts
- Booleans
- Characters
- Strings
- Arrays
- https://kotlinlang.org/docs/basic-types.html
public open class Any { public open operator fun equals(other: Any?): Boolean public open fun hashCode(): Int public open fun toString(): String }The root of the Kotlin class hierarchy. Every Kotlin class has Any as a superclass.
- https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/
코틀린은 기본적으로 원시 타입(primitive type)을 사용하지 않고, 문자/숫자/불리언 타입들도 전부 클래스로 만들고 런타임 시에 원시 타입으로 변환되도록 하고 있다. 어떤 변수든 멤버 함수랑 프로퍼티를 호출할 수 있도록 하기 위함이다.
이렇듯 모든 타입은 Any(자바의 Object)를 상속받도록 하고 있는데, void를 Unit으로 래핑해서 사용하는 것도 같은 이유인 것이다.
참고로 Unit은 특별한 상태나 행동을 가지고 있지 않기 때문에 싱글턴으로 생성되어 실제로는 하나의 인스턴스를 사용한다고 한다.
그런가 하면 Unit과 비슷?하다고 해야할까 Nothing이란 것도 있다. 이것도 클래스이긴 한 모양인데, 인스턴스를 갖지 않는 말 그대로의 無 이다. 이를 함수의 반환형으로 쓰게 되면 "절대로 반환하지 않는다"는 의미를 갖게 된다. 항상 에러를 throw 한다는 것을 명시하는 역할이다.
public final class Nothing private constructor() {}Nothing has no instances. You can use Nothing to represent "a value that never exists": for example, if a function has the return type of Nothing, it means that it never returns (always throws an exception).
- https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-nothing.html
컴파일러에게 정보를 주는 역할도 한다고 한다.
fun fail(message: String): Nothing {
throw IllegalStateException(message)
}
fun getCompany(person: Person) {
val comp = Person.company ?: fail("No company info.")
return comp.name
}
Person.company가 null이면 throw가 발생되므로, 이 줄을 통과한다면 comp는 !null임을 컴파일러가 알게 되어, 널체크 없이 comp.name를 용인해준다고 한다.
참고
어제도 고생하셨어요~👍👍