Null Safety
In an effort to rid the world of NullPointerException
, variable types in Kotlin don't allow the assignment of null
. If you need a variable that can be null, declare it nullable by adding ?
at the end of its type.
fun main() {
var neverNull: String = "This can't be null" // 1
neverNull = null // 2
var nullable: String? = "You can keep a null here" // 3
nullable = null // 4
var inferredNonNull = "The compiler assumes non-null" // 5
inferredNonNull = null // 6
fun strLength(notNull: String): Int { // 7
return notNull.length
}
strLength(neverNull) // 8
strLength(nullable) // 9
}
{validate="false"}
- Declares a non-
null
String variable. - When trying to assign
null
to non-nullable variable, a compilation error is produced. - Declares a nullable String variable.
- Sets the
null
value to the nullable variable. This is OK. - When inferring types, the compiler assumes non-
null
for variables that are initialized with a value. - When trying to assign
null
to a variable with inferred type, a compilation error is produced. - Declares a function with a non-
null
string parameter. - Calls the function with a
String
(non-nullable) argument. This is OK. - When calling the function with a
String?
(nullable) argument, a compilation error is produced.
Working with Nulls
Sometimes Kotlin programs need to work with null values, such as when interacting with external Java code or representing a truly absent state. Kotlin provides null tracking to elegantly deal with such situations.
fun describeString(maybeString: String?): String { // 1
if (maybeString != null && maybeString.length > 0) { // 2
return "String of length ${maybeString.length}"
} else {
return "Empty or null string" // 3
}
}
fun main() {
println(describeString(null))
}
- A function that takes in a nullable string and returns its description.
- If the given string is not
null
and not empty, return information about its length. - Otherwise, tell the caller that the string is empty or null.