Basics

Literals

  • Integer numbers

  • Characters

  • Strings

Variables

  • val (for value) declares an immutable variable (just a named value or a constant), which cannot be changed after it has been initialized (this is actually not entirely true).

It is always possible to change the internal state of a val variable: while it is prohibited to reassign the variable, its content can be modified in some other ways.

// list creation
val myMutableList = mutableListOf(1, 2, 3, 4, 5)
// trying to update the list
myMutableList = mutableListOf(1, 2, 3, 4, 5, 6) // error line
// adding a new element
myMutableList.add(6)   // it works
// printing the list
println(myMutableList) // [1, 2, 3, 4, 5, 6]
  • var (for variable) declares a mutable variable, which can be changed (as many times as needed).

The more mutable variables (those declared with the keyword var) in your code, the harder it is to read.

Remember, immutable variables (those declared with the keyword val) help write more readable code.

  • const modifier is used before the val keyword to declare a compile-time constant.

Data types

Kotlin determines the data types of variables automatically. This mechanism is called type inference.

The type of a variable can also be specified when declaring it:

Functions

All functions return a result, even the println function.

The result is a special value called Unit, which practically means no result. When your function returns nothing, it means it returns Unit, you can think of it as Void.

Last updated

Was this helpful?