Your Int
isn't being cast to a Unit
. It's the other way around, actually. Your () -> Int
lambda is being treated as a () -> Unit
lambda. Specifically, from the docs on lambda expressions (emphasis mine),
The full syntactic form of lambda expressions is as follows:
val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
...
- If the inferred return type of the lambda is not
Unit
, the last (or possibly single) expression inside the lambda body is treated as the return value.
So in your example,
Animal<Unit>().extension { 2+2 }
{ 2+2 }
is not a lambda returning an Int
. It's a lambda returning Unit
, i.e. nothing of value. Kotlin is happy to simply discard the return value of a lambda if it makes type inference work out. That's to allow things like
myButton.addEventListener { event ->
...
someFunctionThatHappensToReturnInt()
}
It would be really annoying if that lambda had inferred return type Int
just because I happened to call a function (for side effects) that returns an Int
, so Kotlin will drop it when necessary.
If you write the word return
explicitly, you'll force the type of the argument to be () -> Int
and will see the error you expect.
Animal<Unit>().extension { return 2+2; }