Kotlin Basics: Variables, Types, Functions and Control Flow

Android Development with Kotlin: 21 Real Projects · Kotlin Basics · 5 min read · Updated

val, var and functions

  1. val stores a value that never changes. Prefer it.
  2. var stores a value you are allowed to change later.
  3. A function takes values in and works on them.
  4. It gives back a result, which your program prints or shows on screen.

Before you build screens, you need to read and write Kotlin comfortably. This lesson covers the parts of the language you will use in every app. Each example is a tiny program with a main function. To run them without making a whole Android project, open the free Kotlin Playground on the official Kotlin website, paste the code and press Run. You can also create a new Kotlin file in Android Studio and run its main function.

Values and variables

Kotlin has two keywords for storing data. val makes a value that cannot be reassigned after it is set. var makes a variable that can change. Prefer val: code is easier to reason about when most things never change. Kotlin works out the type from the value (this is called type inference), so you rarely write the type, but you can.

fun main() {
    val name = "Asha"          // val: cannot be reassigned
    var steps = 4200           // var: can change
    steps += 800

    val goal: Int = 10_000     // the type can be written out
    val ratio = steps.toDouble() / goal
    val percent = (ratio * 100).toInt()

    println("$name walked $steps steps")
    println("That is $percent% of the goal")
    println("Steps left: ${goal - steps}")
}

The $name and ${goal - steps} parts are string templates: Kotlin puts the value into the text. Use $name for a simple name and ${ ... } for any expression. Expected output:

Asha walked 5000 steps
That is 50% of the goal
Steps left: 5000

Common types are Int (whole numbers), Double (numbers with decimals), Boolean (true or false), String (text) and Char (one character). Kotlin does not change types silently. You cannot add an Int to a Double without a conversion such as toDouble(). That strictness stops a whole group of bugs.

Decisions and loops

if works as you expect, and in Kotlin it is also an expression, which means it gives back a value. when is like a more readable chain of if and else if. Loops use for with a range such as 1..3, and while.

fun grade(score: Int): String = when {
    score >= 90 -> "A"
    score >= 75 -> "B"
    score >= 50 -> "C"
    else -> "Try again"
}

fun main() {
    for (i in 1..3) println("Round $i")

    var countdown = 3
    while (countdown > 0) {
        print("$countdown ")
        countdown--
    }
    println("Go!")

    val score = 82
    val label = if (score >= 50) "pass" else "fail"   // if is an expression
    println("$score is a $label, grade ${grade(score)}")
}
Round 1
Round 2
Round 3
3 2 1 Go!
82 is a pass, grade B

Functions

A function is a named piece of code that you can call many times. It lists its inputs (parameters) and its output type after a colon. A function whose body is a single expression can be written with =. You can give parameters default values and call them with named arguments, which makes calls easy to read. vararg lets a function take any number of values.

fun greet(name: String, greeting: String = "Hello"): String = "$greeting, $name!"

fun average(vararg numbers: Int): Double =
    if (numbers.isEmpty()) 0.0 else numbers.sum().toDouble() / numbers.size

fun main() {
    println(greet("Ravi"))
    println(greet("Ravi", greeting = "Welcome"))
    println(average(70, 80, 90))
    println(average())
}
Hello, Ravi!
Welcome, Ravi!
80.0
0.0

Why this matters for Android

Every Android screen you build uses these basics. State is stored in val and var. Buttons run functions. Lists of data are looped over. A when decides which screen part to show. If a later lesson feels hard, the cause is nearly always a gap here, so come back and rerun these samples.

Your task

  1. Run all three samples in the Kotlin Playground and compare each output with the lesson.
  2. Change Variables.kt so the goal is 8,000 steps and the person walked 6,500. Check that the percent and steps left are right.
  3. Write a function isEven(n: Int): Boolean and use it inside a for loop that prints the even numbers from 1 to 10.
  4. Add a when to Control.kt that prints a different message for a score of exactly 100.

How to check it worked

  • Your outputs match the expected text for each sample.
  • You can say the difference between val and var.
  • You can explain what a string template is and write one.

Frequently asked questions

Why does Kotlin prefer val over var?

A value that never changes cannot be changed by mistake somewhere else in the program. That makes bugs easier to find. Use var only when the value really has to change.

Do I need to write types everywhere?

No. Kotlin works out the type from the value. You write a type when it is not obvious, for function parameters (always) and for public APIs.

Where can I run Kotlin without Android Studio?

The Kotlin Playground on the official Kotlin website runs small programs in your browser. Android Studio can also run a main function from any Kotlin file.