liveBook · Manning

Chapter 2: Kotlin basics

What you will learn in chapter 2 of Kotlin in Action, 2E

This chapter introduction previews Kotlin basics and explains what it means to write idiomatic Kotlin.

After this chapter you will be able to

Section by section

Introduction

This chapter introduction previews Kotlin basics and explains what it means to write idiomatic Kotlin.

Key terms: idiomatic Kotlin, idioms, syntactic sugar

2.1 Basic elements: Functions and variables

The section previews the introduction of Kotlin functions and variables, type inference, and a preference for avoiding mutable data.

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

Introduces a minimal Kotlin “Hello, world!” program and uses it to point out basic function and output syntax.

Key terms: fun, main function, top level, entry point, println, Kotlin standard library, semicolon

2.1.2 Declaring functions with parameters and return values

This section explains how to declare and call a Kotlin function with parameters and a return value, and why expressions such as if can supply a result while assignments cannot.

Key terms: fun, parameter, Int, return type, arguments, expression, statement, if, assignment, main

2.1.3 Making function definitions more concise by using expression bodies

This section shows how expression bodies shorten Kotlin functions, how their return types can be inferred, and when explicit return types remain useful.

Key terms: expression body, block body, type inference, return type, inferred return types, public API, signature changes

2.1.4 Declaring variables to store data

This section shows how to declare Kotlin variables and when their types can be inferred from initializers.

Key terms: variable declaration, val, var, type, type inference, initializer expression, Int, Double

2.1.5 Marking a variable as read only or reassignable

This section explains how val and var control reassignment, why val is preferred, and what those declarations do not change about objects or variable types.

Key terms: val, var, read-only reference, reassignable reference, initialized exactly once, val reference, mutable list, read only, String, Int

2.1.6 Easier string formatting: String templates

This section shows how Kotlin string templates insert variables and expressions into strings, including a greeting chosen from user input.

Key terms: string templates, $, string concatenation, expression, curly braces, if expression

2.2 Encapsulating behavior and data: Classes and properties

Introduces Kotlin classes by comparing a simple Java Person class with its shorter Kotlin equivalent and noting Kotlin’s default public visibility.

Key terms: class, property, getter function, boilerplate, public, default visibility

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

Explains how Kotlin properties package class data with accessors and how Java and Kotlin code access them.

Key terms: property, val, var, getter, setter, backing field, property syntax, getName, isStudent, setStudent

2.2.2 Computing properties instead of storing their values: Custom accessors

This section shows how a custom getter can compute a property from other properties and explains when that characteristic is better expressed as a property than a member function.

Key terms: custom getter, property accessor, isSquare, expression-body syntax, type inference, property, member function

2.2.3 Kotlin source code layout: Directories and packages

This section explains how Kotlin packages organize declarations, how imports make declarations available across packages, and how source-file layout relates to package structure.

Key terms: package statement, package, declarations, import, star import, wildcard import, top-level functions, source files, directory structure, package structure

2.3 Representing and handling choices: Enums and when

Introduces Kotlin’s `when` construct as a more powerful, commonly used alternative to Java’s `switch`, while previewing enums and smart casts.

Key terms: when construct, switch construct

2.3.1 Declaring enum classes and enum constants

This section introduces Kotlin enum declarations and shows how color constants can carry properties and methods.

Key terms: enum class, soft keyword, hard keyword, enum constants, r, g, and b, rgb, printColor, semicolon, enum constant list, method definitions

2.3.2 Using the when expression to deal with enum classes

Introduces `when` as a value-returning way to choose behavior for enum constants, including grouped branches and shorter names through imports.

Key terms: when, expression body, when branch, enum constants, break, importing, Color enum class

2.3.3 Capturing the subject of a when expression in a variable

This section shows how to keep a when subject local to the expression and explains why a when used as an expression must cover every possible path.

Key terms: subject, when expression, scope, exhaustive, else

2.3.4 Using the when expression with arbitrary objects

This section uses sets in a when expression to match color pairs regardless of their order.

Key terms: setOf, Set, set comparison, when expression, branch condition, else branch, exhaustive

2.3.5 Using the when expression without an argument

This section shows how an argumentless when expression can check Boolean conditions while avoiding temporary Set objects at a cost to readability.

Key terms: when expression, branch condition, Boolean expression, Set instances, mixOptimized, short-lived objects, garbage collector

2.3.6 Smart casts: Combining type checks and casts

This section uses a simple arithmetic-expression tree to show how Kotlin’s `is` checks enable smart casts when evaluating different object types.

Key terms: Expr, marker interface, Num, Sum, eval, recursively, is, smart cast, val, custom accessor

2.3.7 Refactoring: Replacing an if with a when expression

Shows how to make an `eval` function more concise by using `if` as a value-producing expression, then replacing an `if` cascade with a type-checking `when`.

Key terms: if expression, expression-body syntax, if branch, when expression, when branches, type check, smart cast, Num, Sum

2.3.8 Blocks as branches of if and when

Explains how block branches in if and when produce results, including when they contain logging statements.

Key terms: if, when, block, last expression, expression body, block body

2.4 Iterating over things: while and for loops

Introduces Kotlin’s familiar while loop and the basic syntax of its for loop.

Key terms: while loop, for loop, in

2.4.1 Repeating code while a condition is true: The while loop

The section introduces Kotlin’s while and do-while loops and explains how labels can direct break and continue in nested loops.

Key terms: label, break, continue, while, do-while

2.4.2 Iterating over numbers: Ranges and progressions

This section shows how Kotlin uses ranges and progressions to iterate over numbers, including backward and stepped iteration.

Key terms: range, closed, inclusive, half-closed range, .., ..<, progression, downTo, step

2.4.3 Iterating over maps

This section shows how to iterate over maps, use bracket syntax for map entries, and obtain indices while iterating over a collection.

Key terms: for loop, map, key-value pairs, destructuring syntax, range, map[key], map[key] = value, get, put, withIndex

2.4.4 Using in to check collection and range membership

This section explains how `in` and `!in` check membership in ranges and collections, including within `when` expressions.

Key terms: in, !in, range, when expressions, collections, kotlin.Comparable, String

2.5 Throwing and catching exceptions in Kotlin

Introduces how Kotlin exceptions are thrown and propagated, and shows that throw can be used within an expression.

Key terms: exception, catch, stack, throw, expression

2.5.1 Handling exceptions and recovering from errors: try, catch, and finally

This section explains how Kotlin handles exceptions with try, catch, and finally, and why it does not enforce Java-style checked exceptions.

Key terms: try, catch, finally, BufferedReader, throws clause, checked exceptions, unchecked exceptions, NumberFormatException, IOException, try-with-resources

2.5.2 Using try as an expression

This section shows how Kotlin’s try expression produces a value from either a successful try block or a catch block.

Key terms: try expression, catch block, last expression, catch clause, return statement, fallback values, NumberFormatException

2.6 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 1: Kotlin: What and why Chapter 3: Defining and calling functions →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.