Chapter 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 how to declare in Kotlin the essential elements of any program: variables, functions, and classes. Along the way, you’ll get acquainted with the concept of properties in Kotlin.

You’ll learn how to use different control structures in Kotlin. They’re mostly similar to those that are familiar to you from Java, but enhanced in important ways.

We’ll introduce the concept of smart casts, which combine a type check and a cast into one operation. Finally, we’ll talk about exception handling. By the end of this chapter, you’ll be able to use the basics of the language to write working Kotlin code, even if it might not be the most idiomatic.

2.1. Basic elements: functions and variables

This section will introduce you to the basic elements that every Kotlin program consists of: functions and variables. You’ll see how Kotlin lets you omit many type declarations and how it encourages you to use immutable, rather than mutable, data.

2.1.1. Hello, world!

Let’s start with the classical example: a program that prints “Hello, world!”. In Kotlin, it’s just one function:

Listing 2.1. “Hello World!” in Kotlin

What features and parts of the language syntax can you observe in this simple code snippet? Check out this list:

2.2. Classes and properties

2.3. Representing and handling choices: enums and “when”

2.4. Iterating over things: “while” and “for” loops

2.5. Exceptions in Kotlin

2.6. Summary

sitemap