Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to return Unit.INSTANCE in a void kotlin function, when called from Java, and not NULL?

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?

like image 736
htafoya Avatar asked Jan 25 '23 07:01

htafoya


1 Answers

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.

like image 152
Roland Avatar answered Jan 30 '23 03:01

Roland