Kotlin은 왜 void 대신 Unit을 쓸까 👀

바이너리·2022년 3월 9일
1

Kotlin

목록 보기
2/2
post-thumbnail

코틀린을 하다보면 Unit을 자주 접할 수 있습니다. Unit은 java의 void와 대응되는 wrapper class로, toString을 제외한 어떠한 메서드도 구현되어 있지 않습니다.

package kotlin

/**
 * The type with only one value: the `Unit` object. This type corresponds to the `void` type in Java.
 */
public object Unit {
    override fun toString() = "kotlin.Unit"
}

만약 함수가 반환해야 할 값이 없다면 return type을 Unit으로 지정할 수 있습니다.

fun printHello(name: String?): Unit {
    if (name != null)
        println("Hello $name")
    else
        println("Hi there!")
    // `return Unit` or `return` is optional
}

Unit을 반환하는 함수는 아래 선언처럼 아무 return 값을 반환하지 않게 명시해도 됩니다.

fun printHello(name: String?) { ... }

코틀린은 왜 자바의 void를 그대로 사용하지 않고 Unit이라는 클래스를 만들어서 사용하는 걸까요?

In Kotlin, everything is an object in the sense that we can call member functions and properties on any variable. Some types can have a special internal representation - for example, numbers, characters and booleans can be represented as primitive values at runtime - but to the user they look like ordinary classes. In this section we describe the basic types used in Kotlin: numbers, booleans, characters, strings, and arrays.

코틀린은 기본적으로 원시 타입(primitive type을) 사용하지 않고, 기존의 문자/숫자/부울 값을 표현하던 타입들도 전부 클래스로 만들어 실제 런타임 시에 원시 타입으로 변환되도록 하고 있습니다.
그래서 모든 타입은 Any(자바의 Object)를 상속받도록 하고 있는데, void를 Unit으로 래핑해서 사용하는 것도 같은 이유라고 볼 수 있습니다.

Unit은 특별한 상태나 행동을 가지고 있지 않기 때문에 싱글턴으로 생성되어 실제로는 하나의 인스턴스를 사용합니다.


참고

profile
01101001011010100110100101101110

0개의 댓글