Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 ยท Language Basics

Values, Variables and Types

Learn val vs var, type inference, lazy val, the basic Scala types (Int, Long, Double, Boolean, Char, String), numeric conversions and the Any type hierarchy.

Almost every Scala program begins with names bound to values. Scala gives you val for values that never change and var for ones that do, plus lazy val for values computed on first use. Underneath, there is a clear set of basic types and one type hierarchy that explains how everything fits together. This lesson covers them with read-only Scala, plus runnable Java and Kotlin demos for the behaviours that are shared across the JVM.

val and var

SCALA
val language = "Scala"   // immutable: cannot be reassigned
var score = 0            // mutable: can be reassigned

score = score + 10
// language = "Java"     // error: reassignment to val

Trying to reassign a val is a compile error, not a runtime one. Choose val by default. Reach for var only when you need a loop counter or an accumulator and no immutable alternative reads well.

An important detail: val makes the name unchangeable, not the object. If a val refers to a mutable object, the object can still change:

SCALA
import scala.collection.mutable.ArrayBuffer

val items = ArrayBuffer(1, 2)
items += 3                // allowed: the buffer changes
// items = ArrayBuffer(9) // error: the name cannot be rebound

Java has the same idea with final, which you can see here:

Java final vs mutable object (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Type inference and annotations

The compiler infers a type from the right-hand side. You can also write it explicitly after a colon:

SCALA
val a = 10            // Int
val b: Long = 10      // Long (annotation changes the type)
val c = 10.5          // Double
val d = "hi"          // String
val e: Double = 3     // Int literal widened to 3.0

Write an annotation when the inferred type would be too narrow, when you want to document a public API, or when the type is not obvious (for example an empty collection val names: List[String] = Nil).

Basic types

Type Size / kind Example
Byte 8-bit signed val b: Byte = 127
Short 16-bit signed val s: Short = 1000
Int 32-bit signed 42
Long 64-bit signed 42L
Float 32-bit IEEE 754 1.5f
Double 64-bit IEEE 754 1.5
Char 16-bit Unicode unit 'A'
Boolean true / false true
String text (Java's String) "hello"
Unit no useful value ()

These are real classes in Scala: you can call methods on any of them, such as 42.toString, 3.max(7) or 'a'.isLetter. The compiler still uses the primitive JVM types underneath where it can, so there is no speed penalty.

The runnable Kotlin demo below shows integer overflow, a shared JVM behaviour:

Kotlin Int range and overflow (Kotlin, same JVM rules as Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In Scala you write the same expressions: Int.MaxValue + 1 wraps to -2147483648, and 7 / 2 is 3. For arithmetic that must not overflow, use Math.addExact or switch to Long or BigInt.

Conversions between numeric types

Scala widens automatically when no information can be lost (Int to Long to Double), but narrowing must be explicit:

SCALA
val i: Int = 42
val l: Long = i          // fine, widening
val d: Double = i        // fine
val back: Int = d.toInt  // narrowing: explicit
val c: Char = 65.toChar  // 'A'
val n = "123".toInt      // parse a String

"abc".toInt throws a NumberFormatException. To parse safely, use "abc".toIntOption, which returns None when the text is not a number. We use Option more in later lessons.

Strings are immutable

String is Java's String, with extra Scala methods through an enrichment:

SCALA
val s = "Scala"
s.length          // 5
s.reverse         // "alacS"
s.toUpperCase     // "SCALA"
s(0)              // 'S'
s.take(3)         // "Sca"

Every operation returns a new string. Formatting and interpolation are covered in the operators and strings lesson.

lazy val

A lazy val is evaluated the first time it is used, and the result is cached:

SCALA
lazy val config =
  println("loading config...")
  Map("mode" -> "fast")

println("before")
println(config("mode"))   // prints "loading config..." then "fast"
println(config("mode"))   // just "fast": already computed

The output order is before, loading config..., fast, fast. Use lazy val for expensive values that may never be needed. Avoid it on hot paths because access goes through a thread-safe check.

The type hierarchy

flowchart TD
  Any --> AnyVal
  Any --> AnyRef
  AnyVal --> Int
  AnyVal --> Double
  AnyVal --> Boolean
  AnyVal --> Unit
  AnyRef --> String
  AnyRef --> List
  AnyRef --> UserClasses["Your classes"]
  Null -.-> AnyRef
  Nothing -.-> Any

Any is the root. AnyVal covers value types, AnyRef is java.lang.Object. Nothing is the bottom type.

  • Any is the supertype of everything, so val things: List[Any] = List(1, "two", 3.0) is legal.
  • AnyVal holds the primitive-like types; AnyRef holds everything else.
  • Nothing has no values; it is the type of expressions that never return, such as throw new Exception. Because it is a subtype of everything, if x then 1 else throw ... has type Int.
  • Null is the type of null, which exists for Java interop. Idiomatic Scala avoids null and uses Option.

Constants and naming

For a compile-time constant, annotate with a literal type or use final val:

SCALA
final val MaxUsers = 100

Common mistakes

  • Using var out of habit from other languages. Try val first.
  • Expecting val to freeze an object. It freezes only the binding.
  • Forgetting L on a big literal: val big = 3000000000 fails because it does not fit in an Int; write 3000000000L.
  • Dividing two Int values and expecting decimals.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you reassign a val?

    A val cannot be rebound, and the compiler rejects reassignment.
  2. 2. What is the result of 7 / 2 with Int operands?

    Integer division truncates toward zero, so 7 / 2 is 3.
  3. 3. When is a lazy val's right-hand side evaluated?

    A lazy val runs its initializer once, the first time it is used.
  4. 4. Which type is the root of all Scala types?

    Any is the top type. AnyRef is only the root of reference types, and Nothing is the bottom.

Summary

  • val is immutable binding, var is mutable binding; prefer val.
  • The compiler infers types, and you add annotations where they help.
  • The basic types are Byte, Short, Int, Long, Float, Double, Char, Boolean, String and Unit.
  • Widening is automatic; narrowing needs .toInt and similar.
  • lazy val defers evaluation; Any, AnyVal, AnyRef, Nothing form the hierarchy.

Next: Operators and Strings