Elka
09/10/2020, 5:14 PMfun <T: Any> x(block: () -> T?) {
val res = block()
if (res != null) {
println(res)
} else {
println("returned null")
}
}
fun test() {
x<Unit> {
null
}
}
Kotlin (<1.4)
It prints "retuned null
Kotlin (>= 1.4)
It prints kotlin.Unit
The weird part is that x { null }
works fine. The compiler is able to infer the type to Unit?
. But I can't write x<Unit?> { null }
as the type is bound to Any
which is something we need on Kotlin-Native (unless this has changed too)Tobias Berger
09/10/2020, 7:42 PMUnit
instead of the last statement which is null
, but what you call "the weird part" isn't really weird at all. The type Unti?
isn't inferred, it's specified. The return type of `x`'s lambda parameter is T?
, so because your call explicitly specifies T
as Unit
, the lambda return type is Unit?
ilya.gorbunov
09/10/2020, 10:35 PMElka
09/11/2020, 4:47 AM