Programs need to remember things: a player's score, a user's name, the price of an item in a basket. A variable is a named box that holds a value so you can use it later, and change it if you need to.
Kotlin has two kinds of variable. val creates a value that can't be reassigned once it's set, and var creates one that can. Choosing val wherever possible is one of the habits that makes Kotlin code safe and easy to follow, because you always know a val hasn't quietly changed somewhere else.
In this lesson you'll create variables with both keywords, meet Kotlin's basic types, see how the compiler works out types for you, and convert values from one type to another, for example turning the text "42" into the number 42.
val and var
val name = "Ada" // can't be reassigned
var score = 0 // can change
score = 10
score += 5valis short for value. Tryingname = "Grace"is a compile error: "Val cannot be reassigned".varis short for variable. You can give it a new value any time, as long as it's the same type.- Start with
val, and only switch tovarwhen you genuinely need to change the value. Most variables in good Kotlin code areval.
Types and type inference
Every variable has a type that says what kind of data it holds:
| Type | Holds | Example |
|---|---|---|
Int | Whole numbers | 42 |
Long | Very large whole numbers | 8_000_000_000L |
Double | Decimal numbers | 3.75 |
Boolean | true or false | true |
Char | One character, in single quotes | 'K' |
String | Text, in double quotes | "Kotlin" |
You rarely need to write the type: Kotlin infers it from the value, so val age = 30 is an Int. You can still write it explicitly with a colon: val age: Int = 30. Once set, a variable's type never changes; var score = 0 can't later hold "ten".
Naming rules and constants
- Names can contain letters, digits and underscores, but can't start with a digit.
- Use camelCase:
firstName,totalPrice,isLoggedIn. - Names are case-sensitive:
scoreandScoreare different variables. - Keywords like
val,funandifcan't be used as names.
For fixed values known before the program runs, such as a tax rate, use const val at the top level of the file, outside any function, and write the name in capitals: const val MAX_PLAYERS = 4.
Converting between types
Kotlin never converts types silently, even between number types, which prevents surprises. Convert explicitly with functions:
val text = "42"
val number = text.toInt() // 42
val price = "3.5".toDouble() // 3.5
val label = number.toString() // "42"
val whole = 9.99.toInt() // 9, decimals are droppedIf the text isn't a valid number, toInt() throws an error. toIntOrNull() returns null instead, which you'll learn to handle safely in the null safety lesson.
More number types and literals
Int and Double cover most everyday values, but Kotlin has a full family of number types:
| Type | Size | Use it for |
|---|---|---|
Byte, Short | 8 and 16 bits | Raw data and memory-sensitive arrays |
Int | 32 bits | Counts, ages, ordinary whole numbers |
Long | 64 bits | Large values: file sizes, timestamps, populations |
Float | 32 bits | Decimals where less precision is fine, such as graphics |
Double | 64 bits | Ordinary decimals |
The way you write a literal sets its type. A whole number is an Int, or a Long if it's too big for an Int or ends in L. A decimal is a Double, or a Float if it ends in f:
val population = 8_100_000_000L // Long
val ratio = 1.5f // Float
val million = 1_000_000 // Int, underscores make it readableUnderscores are ignored by the compiler and simply make long numbers easier to read.
Kotlin Variables Syntax
Variables
val name = "Ada" // read-only, type inferred
var count: Int = 0 // changeable, explicit type
count = count + 1
const val TAX_RATE = 0.2 // top level only
val n = "12".toInt()
val maybe = "abc".toIntOrNull() // nullKotlin Variables Summary
valcan't be reassigned;varcan. Preferval.- Basic types: Int, Long, Double, Boolean, Char and String.
- Kotlin infers types from values; write
: Typeto be explicit. - A variable's type never changes after it's declared.
- Convert with toInt(), toDouble(), toString() and toIntOrNull().
Kotlin Variables Examples
Each example shows the code, the output it produces and what each part does.
A small profile
fun main() {
val name = "Priya"
val age = 28
val height = 1.68
val isMember = true
var points = 120
points += 30
println(name)
println(age + 1)
println(height)
println(isMember)
println(points)
}Priya
29
1.68
true
150Line-by-line explanation
- Lines 2 to 5Each type is inferred: String, Int, Double and Boolean.
- Line 6points will change, so it's a var.
- Line 8+= adds to the current value.
- Line 10Arithmetic works on the Int; age itself is unchanged.
Explicit types and constants
const val SHIPPING = 4.99
fun main() {
val items: Int = 3
val itemPrice: Double = 12.50
val total: Double = items * itemPrice + SHIPPING
val initial: Char = 'K'
println(total)
println(initial)
}42.49
KLine-by-line explanation
- Line 1A const val lives outside main and is fixed when the program is compiled.
- Lines 4 to 5Writing the type is optional here, but makes intent clear.
- Line 6Int times Double gives a Double: 37.5 plus 4.99 is 42.49.
- Line 7A Char uses single quotes.
Converting text to numbers
fun main() {
val input = "25"
val years = input.toInt()
println(years * 12)
val bad = "twenty"
println(bad.toIntOrNull())
val price = 19.99
println(price.toInt())
println(years.toString() + " years")
}300
null
19
25 yearsLine-by-line explanation
- Line 3toInt turns the text "25" into the number 25.
- Line 7toIntOrNull gives null instead of crashing on invalid text.
- Line 10Converting a Double to Int drops the decimal part.
- Line 11toString turns the number back into text so it can be joined with +.
Common Kotlin Variables Mistakes
Reassigning a val
val lives = 3
lives = 2 // Val cannot be reassignedvar lives = 3
lives = 2Changing a variable's type
var score = 10
score = "ten" // Type mismatch: inferred type is String but Int was expectedvar score = 10
score = 20Adding a String and a number the wrong way round
val age = 30
val text: String = age + " years" // error: Int has no plus(String)val text = age.toString() + " years"
// or, better, a string template: "$age years"Kotlin Variables in Real Projects
Variables in apps
Android apps store screen state in variables: the text in a search box, whether a switch is on, the list of results. Kotlin's preference for val and its strict types are part of why large apps stay stable: values can't change unexpectedly, and the compiler catches type mix-ups before users ever see them.
Kotlin Variables FAQ
What is the difference between val and const val?
val creates a read-only variable whose value can be calculated while the program runs, such as val today = LocalDate.now(). const val declares a compile-time constant: it must be a String or a basic number or Boolean type known before the program runs, and it can only appear at the top level of a file or inside an object. Use const val for fixed settings such as const val MAX_RETRIES = 3.
Does val make an object unchangeable?
No. val means the variable can't be pointed at a different object, but the object itself may still change. val items = mutableListOf(1) followed by items.add(2) is allowed. For a list that can't change at all, use a read-only List created with listOf.
When should I write the type explicitly?
When it isn't obvious from the value or when you want a different type from the one inferred: val price: Double = 10 won't compile, but val price = 10.0 or an explicit Long for a big counter makes intent clear. Function parameters and public function return types always need written types.
Does Kotlin have primitive types like Java's int?
Not in the code you write: Int, Double and Boolean look like ordinary classes with methods, such as 5.toString(). Behind the scenes the compiler stores them as fast JVM primitives wherever possible, so you get readable code without losing performance.
Can a variable be declared without a value?
Yes, if you give it a type and assign it before it's read: val result: String followed by result = "done" in each branch of an if. The compiler checks that every path assigns it exactly once for a val. Reading it before that is a compile error.
Kotlin Variables Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so count can be changed later.
count = 0
count = 5
What type does Kotlin infer for val x = 4.0?
What does this print?
var a = 5
val b = a
a = 9
println(b)
Which line converts "7" into a number safely, without crashing on bad text?
Where can const val be declared?
Kotlin Variables Quiz
5 questions to check what you learned.
What's the difference between val and var?
- val is for numbers, var for text
- val can't be reassigned; var can
- var is faster
- There's none
What does
9.99.toInt()return?- 10
- 9.99
- An error
- 9
Which type holds a single character?
- Char
- String
- Byte
- Letter
Which name follows Kotlin's naming convention for variables?
- TotalPrice
- totalPrice
- total_price
- TOTALPRICE
Why doesn't Kotlin silently convert an Int to a Double?
- Explicit conversions prevent hidden mistakes and loss of precision
- Doubles aren't supported
- It's a bug
- Ints are always bigger