When having a function, for example:
fun doSomething(action:() -> Unit) {
action.invoke()
}
if I call this from Java the code needs to be:
doSomething(() -> {
//do something
return Unit.INSTANCE
})
I have seen code instead using
doSomething(() -> {
//do something
return null
})
Does it affect sending null
instead of Unit.INSTANCE
? Do Kotlin perform more things by validating that UNIT instance is returned instead?
I think most of the time it will not really matter whether null
or Unit.INSTANCE
is used. However as there is at least 1 case where such a null
is not desirable, you should probably always use Unit.INSTANCE
then.
One such made-up example where not returning Unit.INSTANCE
will cause a problem is the following:
fun doSomething(action:() -> Unit) {
action.invoke() logReturnTime("after action invocation")
}
infix fun Unit.logReturnTime(msg : String) { TODO("logging return time $msg") }
If you would call this and return null
you would get an IllegalArgumentException
, whereas the code would run without problem if you use Unit.INSTANCE
.
That having said, I don't believe this is a good example, but it clearly shows, if anyone operates on that Unit
, then it could fail, so you probably better always use Unit.INSTANCE
and you are safe, regardless on what the receiver does with your function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With