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 introduces 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 Writing your first Kotlin program: Hello, world!

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

Figure 2.1. "Hello World!" in Kotlin
fun main graphic

We can observe a number of features and parts of the language syntax in this simple code snippet already:

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 mutable or immutable

 
 
 
 

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

 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest