2 Kotlin basics

 

This chapter covers

  • Declaring functions, variables, classes, enums, and properties
  • Control structures in Kotlin
  • Smart casts
  • Throwing and handling exceptions

In this chapter, you’ll learn the basics of the Kotlin language required to write your first working Kotlin programs. These include basic building blocks that you encounter all throughout Kotlin programs, like variables and functions. You’ll also get acquainted with different ways of representing data in Kotlin via enums as well as classes and their properties.

The control structures you’ll learn throughout this chapter will give you the tools needed to use conditional logic in your programs as well as iterate using loops. You will also learn what makes these constructs special compared to other languages, like Java.

We’ll also introduce the basic mechanics of types in Kotlin, starting with the concept of a smart cast, an operation that combines a type check and a cast into one operation. You’ll see how this helps you remove redundancy from your code without sacrificing safety. We’ll also briefly talk about exception handling and Kotlin’s philosophy behind it. By the end of this chapter, you’ll already be able to combine these basic bits and pieces of the Kotlin language to write your own working Kotlin code, even if it might not be the most idiomatic.

2.1 Basic elements: Functions and variables

2.1.1 Writing your first Kotlin program: “Hello, world!”

2.1.2 Declaring functions with parameters and return values

2.1.3 Making function definitions more concise by using expression bodies

2.1.4 Declaring variables to store data

2.1.5 Marking a variable as read only or reassignable

2.1.6 Easier string formatting: String templates

2.2 Encapsulating behavior and data: Classes and properties

2.2.1 Associating data with a class and making it accessible: Properties

2.2.2 Computing properties instead of storing their values: Custom accessors

2.2.3 Kotlin source code layout: Directories and packages

2.3 Representing and handling choices: Enums and when

2.4.3 Iterating over maps