Values, Variables & Basic Types

4.1 val, var, def, lazy val

Prefer val. Use var only for local, contained mutation.

val x = 10           // immutable (preferred)
var y = 20           // mutable
y = 30
// x = 11            // error: reassignment to val

lazy val config = { println("loading"); loadConfig() }   // evaluated on first access, once
def now = System.currentTimeMillis()                     // re-evaluated each call

4.2 Basic types

val b: Byte = 1 val s: Short = 1 42, 1_000_000, 0xFF 3.14, 1e10 'a', '\n', 'A' (= 'A') true, false "hello" (java.lang.String) () — like void BigInt, BigDecimal

4.3 Conversions

Numeric widening (Int → Long → Double) happens automatically; narrowing requires explicit conversion.

42.toDouble          // 42.0
3.99.toInt           // 3
"42".toInt           // 42 (throws NumberFormatException)
"42".toIntOption     // Some(42)
"x".toIntOption      // None
65.toChar            // 'A'
'A'.toInt            // 65
1.toString
BigInt(2).pow(100)

4.4 Type annotations

val count: Int = 5
val ratio: Double = 0.5
val names: List[String] = List("a", "b")