Variables, Types & Strings

val vs var, type inference, explicit number conversions, string templates and raw strings.

Kotlin prefers immutability: val declares a read-only reference and var a mutable one. Types are inferred, numbers never convert implicitly, and strings come with templates and a rich set of functions.

The basics

const val is a compile-time constant; val read-only; var mutable.

Int, Long, Double, Boolean, Char are the basic types; 9_000_000_000L needs a Long.

cells.toLong() converts explicitly; toInt() on a too-large Long silently keeps the low 32 bits (410065420 here).

7 / 2 is integer division (3); 7 / 2.0 is 3.5.

substringAfter, substringBefore, split and joinToString cover most text handling.

"""raw strings""" keep backslashes; trimMargin removes the indentation up to |.

Prefer val

val total: Long = cells + big // cells is Int val total: Long = cells.toLong() + big

Kotlin performs no implicit widening between number types in assignments; convert explicitly.

What is the difference between val and const val?

val is read-only and can be computed at run time; const val must be a compile-time constant of a primitive or String type, declared at top level or in an object.