Skip to Main Content
Kotlin Cookbook
book

Kotlin Cookbook

by Ken Kousen
November 2019
Intermediate to advanced content levelIntermediate to advanced
254 pages
4h 55m
English
O'Reilly Media, Inc.
Content preview from Kotlin Cookbook

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" 1
// name = null 2
1

Assignment to a non-null string

2

Assignment to null does not compile

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.

Example ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Kotlin

Functional Kotlin

Mario Arias, Rivu Chakraborty
Kotlin Programming Cookbook

Kotlin Programming Cookbook

Aanand Shekhar Roy, Rashi Karanpuria
Functional Programming in Kotlin

Functional Programming in Kotlin

Runar Bjarnason, Paul Chiusano, Marco Vermeulen
Learning Concurrency in Kotlin

Learning Concurrency in Kotlin

Miguel Angel Castiblanco Torres

Publisher Resources

ISBN: 9781492046660Errata PageSupplemental Content