Unit 식을 보고합니다.
Kotlin의 Unit은 유의미한 것을 반환하지 않는 함수의 반환 타입으로 사용할 수 있습니다.
Unit 타입에서 가능한 값은 Unit 객체 하나뿐입니다.
예:
fun redundantA(): Unit {
return Unit // 불필요. 기본적으로 'Unit'이 반환되며 예상되는 반환 타입과 일치합니다
}
fun requiredA(condition: Boolean): Any {
if (condition) return "hello"
return Unit // 필요한 타입이 'Any'이므로 명시적 'Unit'이 필요합니다
}
fun redundantB(condition: Boolean): Any = if (condition) {
fun ancillary(): Int = 1
println("${ancillary()}")
Unit // 마지막 표현식의 타입이 이미 'Unit'이므로 불필요합니다
} else {
println("else")
}
fun requiredB(condition: Boolean): Any = if (condition) {
1024
Unit // 필요. 없으면 '1024'(Int)가 반환 값이 됩니다
} else {
println("else")
}