Chapter 2. basic types and variables: Being a Variable


There’s one thing all code depends on—variables.

So in this chapter, we’re going to look under the hood, and show you how Kotlin variables really work . You’ll discover Kotlin’s basic types, such as Ints, Floats and Booleans, and learn how the Kotlin compiler can cleverly infer a variable’s type from the value it’s given. You’ll find out how to use String templates to construct complex Strings with very little code, and you’ll learn how to create arrays to hold multiple values. Finally, you’ll discover why objects are so important to life in Kotlinville.

Your code needs variables

So far, you’ve learned how to write basic statements, expressions, while loops and if tests. But there’s one key thing we need to look at in order to write great code: variables.

You’ve already seen how to declare variables using code like:

var x = 5

The code looks simple, but what’s going on behind the scenes?

A variable is like a cup

When you think of a variable in Kotlin, think of a cup. Cups come in many different shapes and sizes—big cups, small cups, the giant disposable cups that popcorn comes in at the movies—but they all have one thing in common: a cup holds something.


Declaring a variable is like ordering a drink from Starbucks. When ...

Get Head First Kotlin 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.