beginner15 min

val vs var and Basic Types

Kotlin's read-only val, mutable var, and basic types with type inference.

What you'll learn

  • Distinguish val (read-only) from var (mutable) and choose val by default
  • Identify Kotlin's basic types (Int, Double, String, Boolean) and how type inference works
  • Use string templates ($variable and ${expression}) instead of concatenation

Explanation

Kotlin has two ways to declare a variable: val (read-only, assigned exactly once, like a constant reference) and var (mutable, can be reassigned). Idiomatic Kotlin strongly prefers val by default, switching to var only when reassignment is genuinely needed -- this preference for immutability reduces a whole category of bugs where a value changes unexpectedly.

Kotlin infers types from the initializer, so val name = "Ada" is inferred as String without writing it explicitly -- though you can write val name: String = "Ada" when you want to be explicit or when there's no initializer to infer from. Basic types include Int, Double, String, and Boolean.

String templates let you embed a variable directly in a string with $variableName, or a full expression with ${expression}: "Total: ${price * quantity}" -- avoiding manual string concatenation with +.

Note that reassigning a val is a compile error, not a runtime warning -- Kotlin catches this mistake before your code ever runs.

Guided lab

Fill in the blank: choosing val vs var

KotlinNot executed
This lab does not run in your browser or on VisaSparkSchools's servers. Read the code, fill in the missing piece, then reveal the completed code and its expected output.

Fill in the missing keyword for a variable that will be reassigned, then predict the output.

fun main() {
    val name = "Ada"
    ____ score = 10
    score = score + 5
    println("$name scored $score")
}

Stuck? Get a hint.

Common mistakes

  • Declaring everything with `var` out of habit, when `val` should be the default choice unless reassignment is genuinely needed.
  • Trying to reassign a `val`, forgetting it's a compile error, not just a convention.
  • Concatenating strings with `+` when a string template ($variable or ${expression}) would be clearer.

Knowledge check

Knowledge check

1. What happens if you try to reassign a val after its initial assignment?
2. What does idiomatic Kotlin recommend as the default variable declaration?
3. What does `"Total: ${price * quantity}"` demonstrate?

Takeaway

Prefer val over var by default, and use string templates ($x / ${expr}) instead of manual concatenation.

Summary

val is read-only, var is mutable; Kotlin infers types from initializers; string templates embed variables/expressions directly in strings.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.