Kotlin Basics

Keywords

ver. 1.0.0

Core Kotlin syntax: functions, variables, classes/properties, control flow, loops, and exceptions

This unit teaches the essential Kotlin syntax so you can write small programs: declaring functions (block and expression bodies), choosing between val and var, using string templates, declaring classes and computed properties, defining enum classes and matching with when (including argument-less when), relying on smart casts, iterating with for/while over ranges, collections and maps, and throwing/catching exceptions with try as an expression.

The unit equips you with Kotlin’s core language features needed to move from reading examples to writing working code. You learn how to declare functions with block bodies (which require an explicit return type) and concise expression bodies (where the compiler can infer the return type). You learn to prefer val (read-only) over var (mutable) and what val guarantees and does not guarantee. String templates let you embed variables and expressions directly in string literals, with compile-time checking.

Class declarations and properties replace much of the boilerplate required in Java: a Kotlin property is a first-class concept and the compiler generates backing fields and accessors for you. You also learn to write computed properties by providing a custom getter instead of storing a value.

You learn to declare enum classes (which can carry properties and methods) and to use when as a powerful replacement for switch: when is an expression, needs no breaks, and can match arbitrary objects. When can also be used without an argument as a clear chain of boolean conditions. The smart cast feature means that after an is check the compiler infers the narrower type and you no longer need explicit casts.

Iteration covers while and do-while as in Java plus a single for-in loop that works over ranges, progressions (.., downTo, step, until), collections and maps (including destructuring iteration). The in operator serves both for iterating and testing membership.

Exception handling uses familiar throw and try/catch/finally syntax, but Kotlin differs from Java in two important ways: there are no checked exceptions (you aren’t forced to catch or declare them), and try is an expression that yields a value.

By the end of the unit you can declare functions and variables, define classes with stored or computed properties, use when and smart casts for concise branching, iterate with ranges and collection loops, and handle exceptions idiomatically—preparing you to move on to shaping and calling functions in more detail.

Materials

Source document

  • Kotlin in Action, Second Edition, Sebastian Aigner, Roman Elizarov, Svetlana Isakova, and Dmitry Jemerov, Manning, April 2024 — Link — Page 21-50