Type Inference
Prerequisites: Data types
You rarely need to write types for values — the compiler infers them from the right-hand side:
@main def inference(): Unit =
val count = 42
val price = 20.5
val words = List("a", "b")
val mixed = List(1, 2.5)
val pairs = Map("one" -> 1)
println(count / 5)
println(price / 5)
println(mixed)
println(pairs("one") + 1)
8
4.1
List(1.0, 2.5)
2
countis anInt,priceaDouble,wordsaList[String], andpairsaMap[String, Int]. That is whycount / 5is whole-number division (8), whileprice / 5keeps the decimals.List(1, 2.5)mixes anIntand aDouble, so Scala widens theInttoDouble.- Inferred types are just as strict as written ones:
count = "x"would still be an error.
(Hover over a name in VS Code or IntelliJ to see its inferred type, or look at the REPL's output.)
When to write types
- Method parameters — always required.
- Public method return types — recommended; they document the API and give clearer errors.
- When the inferred type isn't what you want:
@main def explicit(): Unit =
val ratio: Double = 3
val scores: List[Double] = List(1, 2, 3)
println(ratio)
println(scores)
3.0
List(1.0, 2.0, 3.0)