Are constructor parameters checked for null when called from Java?

The documentations says:

Null-safety
When calling Kotlin functions from Java, nobody prevents us from passing null as a non-null parameter. That’s why Kotlin generates runtime checks for all public functions that expect non-nulls. This way we get a NullPointerException in the Java code immediately.

Is this true for constructors, too?

Does the compiler generate a null-check for the parameter x in the following case?

class Example(val x: String)

Or do I have to enforce it with an explicit null-check for Java interoperability?

class Example(val x: String) {
    init {
        if (x == null) throw NullPointerException()
    }
}

Tip:
Paste this in IntelliJ

class Example(val x: String)

menu: Tools/Kotlin/Show Kotlin Bytecode and then press button “Decompile”

1 Like

Thanks!

To answer the question myself: It looks like a null-check:

  public <init>(Ljava/lang/String;)V
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   L0
    ALOAD 1
    LDC "x"
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V

Doesn’t this code add (a little) overhead for Kotlin usage, too?

Probably not much

https://willowtreeapps.com/ideas/kotlins-hidden-costs-android-benchmarks

Disclaimer: I build real-time application, this aspect is really far to become an issue :wink: