Question Mark in Kotlin

While I am learning Kotlin, I notice some variables appended by a question mark. It is not common in other programming languages, so I do some search and got answer from Google.

In Kotlin, programmer could express nullability explicitly in the type of a variable. By appending a question mark to the type, we let the compiler (and other programmers) know that the variable is nullable.

When we try to assign null to a variable of non-nullable type:

var x: Int = null
// Doesn't compile:
// non-null.kt:1:14: error: null can not be a value of a non-null type Int
// var x: Int = null

After appending the question mark, it is possible for the variable to hold null:

var y: Int? = null
// null

Safe call operator

In order to call a member function on a variable of nullable type, the safe call operator (?.) is one of the possible ways. If we try to call a member function the usual way, we get an error:
// Doesn't compile:
// hello.kt:5:4: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int?

Though if we use the safe call operator, we get a different result:

// null

Leave a Reply