Scala Language Type Inference Limitations to Inference


Example

There are scenarios in which Scala type-inference does not work. For instance, the compiler cannot infer the type of method parameters:

def add(a, b) = a + b  // Does not compile
def add(a: Int, b: Int) = a + b // Compiles
def add(a: Int, b: Int): Int = a + b // Equivalent expression, compiles

The compiler cannot infer the return type of recursive methods:

// Does not compile
def factorial(n: Int) = if (n == 0 || n == 1) 1 else n * factorial(n - 1)
// Compiles
def factorial(n: Int): Int = if (n == 0 || n == 1) 1 else n * factorial(n - 1)