Search code examples
kotlinnullable

How to avoid !! in a function which returns a non-nullable


In the sample below, the function should return a non-null data. Since the data could be changed in the process, it needs to be var, and can only be nullable to start with.

I can't use lateinit because the first call of if (d == null) will throw.

After the process it will be assigned a non-null data, but the return has to use the !! (double bang or non-null assertion operator).

What is the best approach to avoid the !!?

fun testGetLowest (dataArray: List<Data>) : Data {
   var d: Data? = null
   for (i in dataArray.indecs) {

       if (d == null) {// first run
           d = dataArray[i]
       } else if {
           d.level < dataArray[i].level
           d = dataArray[i]
       }
    }
    return d!!
}

Solution

  • If you don't like !! then supply a default value for it. You'll realize you can only supply the default value if the list is not empty, but, as you said, the list is already known to be non-empty. The good part of this story is that the type system doesn't track list size so when you say dataArray[0], it will take your word for it.

    fun testGetLowest(dataArray: List<Data>) : Data {
        var d: Data = dataArray[0]
        for (i in 1 until dataArray.size) {
            if (d.level < dataArray[i].level) {
                d = dataArray[i]
            }
        }
        return d
    }