CodeBlanks Logo Icon CodeBlanks

Summary - Variables

Combine val, var, const and lateinit to write a profile program.

Summary - Variables

So far you've learned val, var, type inference, const, lateinit and by lazy. val is immutable, var is mutable. The type is usually inferred.

const val is computed at compile-time, lateinit is assigned later, by lazy is computed on first access. Each tool addresses a different deferral need.

Practice Put it together

At the top level, declare const val MULTIPLIER = 2. Inside fun main(), declare var counter = 5, update with counter = counter * MULTIPLIER, and print with println(counter).

Sample solution

Main.kt
const val MULTIPLIER = 2

fun main() {
    var counter = 5
    counter = counter * MULTIPLIER
    println(counter)
}

Expected output

10

Next step

Congratulations! You've completed the variables group. In the next group you'll examine data types in detail: integers (Int, Long), floating-point (Double, Float), Boolean, Char, String and Any/Unit. Each type has a different memory width and use case.

Which type you choose depends on the size and nature of the value. Ready? Let's go.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is mutable?

  • val
  • const val
  • by lazy
  • var Correct answer

Explanation: A variable declared with var can be reassigned.

2 Match the concepts

Term Meaning
val Immutable
var Mutable
const val Compile-time
lateinit Assigned later

3 Summary - Variables: fill in the missing part

Question
var counter = 0
counter ____ 5
Answer
var counter = 0
counter = 5

Explanation: A var variable is reassigned with =.

All lessons in Beginner