Unit
表达式。
Kotlin 中的 Unit
可以用作不返回任何有意义的函数的返回类型。
Unit
类型只有一个可能的值,即 Unit
对象。
示例:
fun redundantA(): Unit {
return Unit // redundant, 'Unit' is returned by default and matches the expected return type
}
fun requiredA(condition: Boolean): Any {
if (condition) return "hello"
return Unit // explicit 'Unit' is required since the expected type is 'Any'
}
fun redundantB(condition: Boolean): Any = if (condition) {
fun ancillary(): Int = 1
println("${ancillary()}")
Unit // redundant since the last expression is already of type 'Unit'
} else {
println("else")
}
fun requiredB(condition: Boolean): Any = if (condition) {
1024
Unit // required, otherwise '1024' (Int) would be the return value
} else {
println("else")
}