Null is a special value that indicates that the value of a var
or val
does not exist.
In many programming languages, including Java, null is a common cause of crashes, because a nonexistent value cannot be asked to do anything.
Kotlin requires a specific declaration if a var
or val
can accept null as a value, which helps avoid this type of crash.
In this chapter, you will learn why null causes a crash, how Kotlin protects against null by default at compile time, and how to safely work with nullable values in Kotlin when you require them. You will also see how to work with what are called exceptions in Kotlin, indicators that something went wrong in your program.
To see these issues in action, you will be updating the NyetHack project. You will add a tavern to the game that accepts user input and attempts to fulfill custom drink requests for its choosy patrons. You will also add a dangerous sword juggling feature.