Instruction

Variables in Kotlin

In a programming language, a variable is a location in memory where you store a value. Based on the kind of variable, its value can change during the program’s execution or stay the same.

In Kotlin, you should declare a variable before it’s used. You’ll get a syntax error if a variable is used without declaring it. Kotlin offers two kinds of variables.

Declaring Immutable Variables

Immutable variables, once assigned a value, can’t be reassigned. You can think of an immutable variable like a sealed box. Once you seal something inside the box, you can’t change what’s inside. You can look at it and use it, but you can’t put something else in the box.

In Kotlin, you declare immutable variables using the val keyword.

Here’s an example of what that looks like:

val greeting = "Hello World"

In the example snippet above:

  • greeting is an immutable variable that’s assigned the value “Hello World”.
  • If you try to assign a different value to greeting later in your code, the compiler will give you an error.

Declaring Mutable Variables

Mutable variables are variables whose values can be reassigned after they’ve been initialized. You can think of mutable variables like a box you can open and close to change its contents. You can put something in the box, take it out, and put something else in.

In Kotlin, you declare mutable variables using the var keyword.

Here’s an example of what that looks like:

var greeting = "Hello World"

In the code snippet above, greeting is a mutable variable that’s initialized with the value “Hello World”.

Later in your code, you can reassign greeting to hold a new value as follows:

greeting = "Goodbye World"

After this line, greeting will now hold the value “Goodbye World”.

In the next chapter, you’ll learn about different data types these variables will store.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo