Home > Software engineering >  Is it safe to make this assumption about Unit / void in Kotlin?
Is it safe to make this assumption about Unit / void in Kotlin?

Time:09-29

I'm currently working with a semaphore in a complicated rxjava chain (in Kotlin) that might be disposed and have a use case with a Unit/void variable.

I wanted to ask about my assumption that in line 3, the unit variable is guaranteed to be non-null. I have never had to use a Unit/void variable (except when specifying higher order functions like () -> Unit), so I am not sure if my assumption that unit is guaranteed to be a non-null Unit type variable in line 3 is a valid assumption. Especially since the java function is void and kotlin uses Unit, it seems a little iffy. What are your thoughts?

var unit: Unit? = null
unit = someJavaApi.someJavaVoidFunction() // java void function
// line 3: is unit guaranteed to be non-null here? I don't see why it would not be, but with java void vs kotlin Unit, it makes me a little worried.

CodePudding user response:

Yes, this is guaranteed.

There is no strange magic involved here, Kotlin just uses Unit singleton if we use the result of a void function. We can see this in the bytecode:

2: invokestatic  #63                 // Method MyJavaClass.someJavaVoidFunction:()V
5: getstatic     #69                 // Field kotlin/Unit.INSTANCE:Lkotlin/Unit;
8: astore_0

Kotlin code:

fun test() {
    var unit: Unit? = null
    unit = MyJavaClass.someJavaVoidFunction()
    println(unit)
}
  • Related