Discuss the concept of 'Type Inference' in Scala.

Instruction: Explain what 'Type Inference' is and how Scala utilizes it, including examples.

Context: This question evaluates the candidate's understanding of Scala's ability to infer types, reducing the verbosity of code without sacrificing type safety.

Updated

Scala's compiler infers many expression, local-value, generic-argument and method-result types from available static information. This reduces annotations without turning Scala into a dynamically typed language.

Ordinary method parameters still need declared types. This is valid Scala 3:

def add(a: Int, b: Int) = a + b

@main def inferenceExample(): Unit = {
  val x = 10
  val numbers = List(1, 2, 3)
  val doubled = numbers.map(n => n * 2)
  val sum: Int = add(x, 5)
  assert(sum == 15)
  assert(doubled == List(2, 4, 6))
}

The result type of add is inferred as Int. The compiler infers numbers as List[Int], and the expected function type of map lets it infer the lambda parameter n. In contrast, def add(a, b) = a + b is invalid; the compiler does not guess method parameter types from arithmetic.

Recursive methods need an explicit result type. Public API result annotations also make contracts visible and can prevent an implementation change from unintentionally changing the inferred API. Empty collections, widening and complex contextual arguments may benefit from explicit types when the inferred type is too narrow or does not match the design. Type inference and its limits

Inference moves type spelling from the source into the compiler's analysis. It does not remove static checks, validate business rules, or guarantee that every unannotated expression has the intended type.

Related Questions