Search code examples
javaunit-testingkotlinassertassertion

Why is it valid to call a void function within Assert.assertNotNull?


Take for example the following pseudo-code,

Assert.assertNotNull(cut.func())

Where cut is a non-null class under test, and func() is some function that returns void.

Furthermore, assuming func() does not throw any errors this will result in a valid assertion.

Since it isn't possible to set an object to be null from within itself in Java / Kotlin, (i.e. func() cannot set cut to null), why is it valid to call void functions within non-null assertions?

Is it simply because void is not the same as null?


Solution

  • Java's void return type is mapped to the Unit object in Kotlin, and Unit is not null.

    val x = System.out.println("") // void Java method
    
    println(x == null) // "false"
    println(x == Unit) // "true"