Chapter 2. Basic Kotlin
This chapter contains recipes that work with the fundamentals of Kotlin. They show you how to use the language without relying on specific libraries.
2.1 Using Nullable Types in Kotlin
Problem
You want to ensure that a variable is never null.
Solution
Define the type of a variable without a question mark. Nullable types also combine with the safe call operator (?.
) and the Elvis operator (?:
)
Discussion
The most attractive feature of Kotlin may be that it eliminates almost all possible nulls. In Kotlin, if you define a variable without including a trailing question mark, the compiler will require that value to be non-null, as in Example 2-1.
Example 2-1. Declaring a non-nullable variable
var
name
:
String
// ... later ...
name
=
"Dolly"
// name = null
Declaring the name
variable to be of type String
means that it cannot be assigned the value null
or the code wonât compile.
If you do want a variable to allow null
, add a question mark to the type declaration, as in Example 2-2.
Get Kotlin Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.