Search code examples
nullpointerexceptionkotlintype-safetykotlin-null-safety

Elvis Operator vs Non-Null Assertion: Diff Between These Statements?


Trying to understand null safety in Kotlin: both of these following statements seem to work fine and be interchangeable in my program:

var y1: Double = 0.0
    get() = when(hasParent) {
        true -> parent!!.y1
        else -> field
    }

and

var y1: Double = 0.0
    get() = parent?.y1!!

(hasParent is simply a getter to see if parent is null or not)

Are these two semantically the same or are they actually different expressions that mean different things? And if they mean the same thing semantically, is the first ever preferred over the second for any reason?


Solution

  • In this case you don't need hasParent. The form which is applicable is this:\

    var y1: Double = 0.0
        get() = parent?.y1 ?: field
    

    The problem with your second getter is that it will try to return the parent.y1 no matter what and it will throw a NullPointerException if it is not there.

    If you use IDEA you'll get warnings for these kinds of problems so they are an easy fix, but you need to be aware of the so called platform types which come from Java code:

    val queue: Queue<String> = LinkedList()
    queue.peek().toInt()
    

    Here the compiler won't complain for .toInt() although it is possible to get a null from the Queue. I've written about this here.