Skip to content
AgileLogics
3 min read

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
  • count is an Int, price a Double, words a List[String], and pairs a Map[String, Int]. That is why count / 5 is whole-number division (8), while price / 5 keeps the decimals.
  • List(1, 2.5) mixes an Int and a Double, so Scala widens the Int to Double.
  • 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)