kotlin: No nullable safety with Java libraries
The Kotlin compiler protects us against type errors, including nullability, within Kotlin code but there are some edges to look out for.
Java library code
Kotlin will not allow a Kotlin method expecting a reference type Foo
to be passed a Foo?
.
Kotlin will allow a Java method expecting a reference type Foo
to be passed a Foo?
! (so long as that's a reference type)
// Given kotlin method:
fun doIt(f: Foo) { }
val a: Foo? = null
doIt(a) // ❌ Will not compile
// Given java.time.Instant library method:
// bool compareTo(Instant) { }
val a: Instant? = null
Instant.now().compareTo(a) // 😱 Will compile, but throw NullPointerException at runtime
Direction of comparison operator
Kotlin will not allow an operator comparison between Kotlin types Foo
and Foo?
.
Kotlin will allow an operator comparison between Java types Foo
and Foo?
but not between Foo?
and Foo
!
// Given Kotlin type Foo:
val k1: Foo = Foo()
val k2: Foo? = null
k1 < k2 // ❌ Will not compile
k2 < k1 // ❌ Will not compile
// Given Java type Instant:
val j1: Instant = Instant.now()
val j2: Instant? = null
j1 < j2 // 😱 Will compile, but throw NullPointerException at runtime
j2 < j1 // ❌ Will not compile
Published on: 29 Jun 2023