Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 3 / 68

Working with Variables

In this lesson you will learn the basics of variables in Kotlin and the difference between the two declaration keywords, val and var. This is for anyone searching for "Kotlin val var how to use".

A variable is like a labelled box that stores a value under a name. val is for a value you will not change and var for one you will. Writing ${variableName} inside a string embeds the value.

The sample code declares two constants, val name = "Alice" and val age = 14, and embeds them with a string template. Reaching for val by default guards against accidental rewrites, which reflects Kotlin's safety-first design philosophy.

A common stumbling block for beginners is choosing between val and var. The rule is val when the value never changes and var when it might, but until that becomes a habit it is easy to over-use var and end up with less idiomatic, less safe code.

In real-world development, type inference lets you leave the types out and start writing concisely - another part of Kotlin's appeal.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)