Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 134 ยท Getting Started

Variables: val and var

Learn Kotlin variables: val (read-only) vs var (mutable), type inference, explicit types, naming rules, const val, shadowing and late initialization, with runnable examples.

A program is mostly about remembering things for a while: a name, a score, a price, a list of messages. A variable is a name attached to a value so you can use it again later. Kotlin gives you two keywords for creating one, val and var, and the difference between them is one of the most important design choices in the language. Once you understand it, you will write safer code almost automatically.

This lesson covers val and var, how the compiler infers types, how to write them explicitly, naming conventions, compile-time constants, shadowing, and declaring a variable now but giving it a value later.

val: a value that does not change

Use val (short for value) to give a name to something that is set once.

Kotlin Declaring values with val

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

After the first assignment, a val cannot point at a different value. That is called read-only (some call it immutable, which is slightly different; see the note below). Trying to reassign it is a compile error, and a helpful one:

Kotlin Reassigning a val (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers main.kt:3:5: error: 'val' cannot be reassigned. The cure is either to remove the second assignment or to decide that the variable really should change and declare it with var.

var: a value that can change

Use var (short for variable) when the value changes during the program: a counter, a running total, the current state of a game.

Kotlin Changing a var

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A var can be given a new value of the same type as before, but never a value of another type. You cannot turn an Int variable into text halfway through; Kotlin is statically typed.

Kotlin A var keeps its type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The error is main.kt:3:9: error: assignment type mismatch: actual type is 'String', but 'Int' was expected. This protects you: anywhere age appears, it is certainly a number.

Which one should I pick?

Start with val. Switch to var only when the compiler tells you that you need to reassign. Reasons professionals give:

  • A val is easier to reason about. When you read code and see val total = ... you know total has this value from here to the end of the scope.
  • Fewer changing values mean fewer places for bugs to hide, especially when code runs on several threads.
  • The IDE warns when a var is never reassigned, suggesting val.

val makes the reference read-only, not necessarily the object it points to. A val that holds a mutable list still lets you add items to that list; you just cannot make the name refer to a different list. Read-only, not deeply immutable. We return to this in Collections Overview.

Type inference and explicit types

So far you have never written a type. Kotlin looked at the value on the right and worked it out: "Kotlin" is a String, 2016 is an Int, 3.14159 is a Double. This is type inference. You can always spell the type out after a colon:

Kotlin Explicit types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

When should you write the type?

  • Usually not, when the value makes it obvious. val count = 0 needs no : Int.
  • When you want a different type than the default, for example val ratio: Float = 0.5f, or val big: Long = 5 (a plain 5 would be an Int).
  • When the value is not there yet (see below) or when you want the code to document an important type, such as a public function's result.
  • For an empty collection, because there is nothing to infer from: val names: MutableList<String> = mutableListOf().
Kotlin Explicit type changes the number type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

All of these print what you would expect; the thing to notice is that the type is a fact about the variable, decided once at compile time.

Naming variables

The compiler accepts letters, digits and underscores, and a name cannot start with a digit. By convention:

  • Variables and functions use camelCase: userName, totalPrice, isReady.
  • Classes use PascalCase: ShoppingCart.
  • Constants use UPPER_SNAKE_CASE: MAX_RETRIES.
  • Names say what the value means, not what it is: maxRetries beats n, and elapsedSeconds beats time.
  • Booleans read well as questions: isEmpty, hasAccount, canEdit.

Names that clash with Kotlin's keywords (like val or class) can be put in backticks, as in `class`, though you should avoid it. Backticks also allow spaces in names, which is occasionally used for test names (see Testing in Kotlin). Kotlin also lets you use any Unicode letter, so grรถรŸe or ๅๅ‰ compile fine, but stick to plain English names in shared code.

Declaring first, assigning later

A val does not need its value on the same line, but it must be assigned exactly once before it is used, and you must give the type because there is nothing to infer from. This is handy when the value depends on a condition.

Kotlin Deferred initialization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both branches assign message, so the compiler is satisfied. If one path forgets, you get an error like variable 'message' must be initialized. In practice you will often write this more cleanly with if as an expression: val message = if (temperature > 30) "Hot" else "Pleasant". That is the topic of if as an Expression.

Kotlin Using a variable before it has a value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You get main.kt:3:13: error: variable 'greeting' must be initialized. Unlike some older languages, Kotlin never hands you a garbage default value such as null or 0 for a local variable. It forces you to give it a real value first.

Compile-time constants: const val

A val is assigned once, but its value may be computed when the program runs. A compile-time constant is known when the program is compiled. Declare one with const val, at the top level of a file or inside an object. Only primitive types and String are allowed, and the value must be a literal or a simple expression of other constants.

Kotlin const val

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler replaces every use of a const val with its value, so it is as cheap as writing the literal, and it can be used in annotations (which must be compile-time constants). Use const val for fixed magic numbers and labels; use plain val for everything else.

Shadowing

If you declare a name that already exists in an outer scope, the new one shadows the old one inside its own block. It is legal but easily confusing, so avoid it.

Kotlin Shadowing in an inner scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output shows 1, 99, 1. Shadowing does not change the outer variable; it only hides it. IDEs usually highlight it with a "name shadowed" hint, and readers get confused by it, so rename the inner variable.

Declaring two variables with the same name in the same scope is a hard error (conflicting declarations), not shadowing.

Scope: where a variable lives

A variable exists from its declaration to the end of the block (the nearest pair of braces) that contains it. Outside that block it is unknown.

Kotlin Variable scope (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler complains main.kt:6:13: error: unresolved reference 'square'. because square was born inside the loop body and is gone after the closing brace. Keep variables in the smallest scope that works: it limits what code can touch them and makes mistakes easier to spot.

Destructuring and multiple values

You can unpack several values at once. This is a preview; the full story is in Pairs, Triples and Destructuring.

Kotlin Declaring two variables at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Using var everywhere "just in case". Prefer val; the compiler will tell you when var is needed.
  • Writing types that add nothing (val x: Int = 5). It is not wrong, only noise.
  • Reusing one variable for different meanings (val result first as a price, then as a message). Create separate, well-named values.
  • Shadowing by accident. Rename the inner one.
  • Expecting val to freeze an object. It only locks the name.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if you assign a new value to a val after it was initialized?

    A val is read-only. The compiler rejects reassignment, so the mistake never reaches a running program.
  2. 2. Given var count = 10, which line does NOT compile?

    The inferred type of count is Int. A var can change its value but not its type, so assigning a String is a type mismatch.
  3. 3. Which declaration is a compile-time constant?

    Only const val (top level or in an object, with a primitive or String value) is replaced by the compiler with its literal value.
  4. 4. What is printed by this code? val x = 1; if (x > 0) { val x = 2 }; println(x)

    The inner x shadows the outer one only inside the braces. Outside the block the outer x, which is 1, is visible again.
  5. 5. When must you write a type explicitly, as in val total: Int?

    The compiler infers a type from the initial value. Without one, there is nothing to infer from, so you must state the type.

Summary

  • val creates a read-only variable (assigned once); var creates one that can be reassigned. Prefer val.
  • Types are inferred from the initial value, and a variable never changes its type. Write a type explicitly when you want a specific one, or when there is no initial value.
  • A val can be assigned later, but exactly once and before use.
  • const val defines a compile-time constant for primitives and strings at the top level or in an object; use UPPER_SNAKE_CASE for it.
  • Names use camelCase, and describe meaning.
  • Shadowing hides an outer name inside a block; scope ends at the closing brace.

Next: Basic Types