Kotlin – Elvis Operator
When you need to define not null a variable which get value from another value that may be null, you can use Elvis operator. Elvis operator is an operator that can use to change null value with another value you want. Lets check it by code:
var data: Double? = null println(data) // output: null // this one set value from "data" var number: Double = data // this line will cause an error, because it have not null type println(number)
you can change error line like this:
var number: Double? = data println(number) // output: null
And what if I want is make a value that automatically insert “0.0” when data have null value. You can use Elvis operator like this:
var numberNotNull: Double = data ?: 0.0 println(numberNotNull) //output: 0.0
Elvis operator change the value..