Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it safe to make this assumption about Unit / void in Kotlin?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading