Kotlin Variables and Types

Store values with val and var, understand Kotlin's basic types, let the compiler infer types, and convert between them.

Lesson 2 of 43Beginner18 min read

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

Kotlin
val name = "Ada"     // can't be reassigned
var score = 0        // can change
score = 10
score += 5
  • val is short for value. Trying name = "Grace" is a compile error: "Val cannot be reassigned".
  • var is 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 to var when you genuinely need to change the value. Most variables in good Kotlin code are val.

Types and type inference

Every variable has a type that says what kind of data it holds:

TypeHoldsExample
IntWhole numbers42
LongVery large whole numbers8_000_000_000L
DoubleDecimal numbers3.75
Booleantrue or falsetrue
CharOne character, in single quotes'K'
StringText, 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: score and Score are different variables.
  • Keywords like val, fun and if can'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:

Kotlin
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 dropped

If 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:

TypeSizeUse it for
Byte, Short8 and 16 bitsRaw data and memory-sensitive arrays
Int32 bitsCounts, ages, ordinary whole numbers
Long64 bitsLarge values: file sizes, timestamps, populations
Float32 bitsDecimals where less precision is fine, such as graphics
Double64 bitsOrdinary 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:

Kotlin
val population = 8_100_000_000L   // Long
val ratio = 1.5f                  // Float
val million = 1_000_000           // Int, underscores make it readable

Underscores 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()   // null

Kotlin Variables Summary

  • val can't be reassigned; var can. Prefer val.
  • Basic types: Int, Long, Double, Boolean, Char and String.
  • Kotlin infers types from values; write : Type to 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.

Example 1

A small profile

Kotlin
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)
}
Output
Priya
29
1.68
true
150
Line-by-line explanation
  1. Lines 2 to 5Each type is inferred: String, Int, Double and Boolean.
  2. Line 6points will change, so it's a var.
  3. Line 8+= adds to the current value.
  4. Line 10Arithmetic works on the Int; age itself is unchanged.
Example 2

Explicit types and constants

Kotlin
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)
}
Output
42.49
K
Line-by-line explanation
  1. Line 1A const val lives outside main and is fixed when the program is compiled.
  2. Lines 4 to 5Writing the type is optional here, but makes intent clear.
  3. Line 6Int times Double gives a Double: 37.5 plus 4.99 is 42.49.
  4. Line 7A Char uses single quotes.
Example 3

Converting text to numbers

Kotlin
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")
}
Output
300
null
19
25 years
Line-by-line explanation
  1. Line 3toInt turns the text "25" into the number 25.
  2. Line 7toIntOrNull gives null instead of crashing on invalid text.
  3. Line 10Converting a Double to Int drops the decimal part.
  4. Line 11toString turns the number back into text so it can be joined with +.

Common Kotlin Variables Mistakes

Reassigning a val

Don't
val lives = 3
lives = 2              // Val cannot be reassigned
Do
var lives = 3
lives = 2

Changing a variable's type

Don't
var score = 10
score = "ten"          // Type mismatch: inferred type is String but Int was expected
Do
var score = 10
score = 20

Adding a String and a number the wrong way round

Don't
val age = 30
val text: String = age + " years"     // error: Int has no plus(String)
Do
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.

Fill in the blankseasy

Complete the code so count can be changed later.

 count = 0
count = 5
Predict the outputeasy

What type does Kotlin infer for val x = 4.0?

Predict the outputmedium

What does this print?

var a = 5
val b = a
a = 9
println(b)
Multiple choicemedium

Which line converts "7" into a number safely, without crashing on bad text?

Multiple choicehard

Where can const val be declared?

Kotlin Variables Quiz

5 questions to check what you learned.

  1. 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
  2. What does 9.99.toInt() return?

    • 10
    • 9.99
    • An error
    • 9
  3. Which type holds a single character?

    • Char
    • String
    • Byte
    • Letter
  4. Which name follows Kotlin's naming convention for variables?

    • TotalPrice
    • totalPrice
    • total_price
    • TOTALPRICE
  5. 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