Kotlin prevents you from assigning a null value to a variable of a non-nullable type. If you want a value to be nullable, you must explicitly opt-in.
To mark the type as nullable, place a question mark after the name of the type, like String?.
How to work with the possibility of null
Checking for null with if/else statement
if(quest != null){
// Safe to use `quest`
println(quest.showQuest())
}Using the safe call operator (?.)
val theQuest = quest?.showQuest()
if(theQuest != null){
println(theQuest)
}
// Using `let`
val theQuest = quest?.showQuest()
theQuest.let {
println(theQuest)
}
// using `it` default param
quest?.showQuest()?.let { println(it) }
// same as => .let { theQuest -> println(theQuest) }Using non-null assertion operator (!!)
There are situations where using the double-bang operator is appropriate. Perhaps you do not have control over the type of a variable, but you are sure that it will never be null. As long as you are confident that the variable you are using will not be null when you use it, then !! is an option.
val playerLevel = readLine()? // using safe call operator
.toIntOrNull() // casting the string from stdin
?: 0 // Using the Elvis Operator
// ^ If left hand is null, use the right hand