Questions And Answers

More Tutorials

Scala Type Inference


Local Type Inference

Scala has a powerful type-inference mechanism built-in to the language. This mechanism is termed as 'Local Type Inference':

val i = 1 + 2 // the type of i is Int
val s = "I am a String" // the type of s is String
def squared(x : Int) = x*x // the return type of squared is Int

The compiler can infer the type of variables from the initialization expression. Similarly, the return type of methods can be omitted, since they are equivalent to the type returned by the method body. The above examples are equivalent to the below, explicit type declarations:

val i: Int = 1 + 2
val s: String = "I am a String"
def squared(x : Int): Int = x*x

Type Inference And Generics

The Scala compiler can also deduce type parameters when polymorphic methods are called, or when generic classes are instantiated:

case class InferedPair[A, B](a: A, b: B)
val pairFirstInst = InferedPair("Husband", "Wife") //type is InferedPair[String, String]
// Equivalent, with type explicitly defined
val pairSecondInst: InferedPair[String, String]
 = InferedPair[String, String]("Husband", "Wife")

The above form of type inference is similar to the Diamond Operator, introduced in Java 7.

Limitations to Inference

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)


In this page (written and validated by ) you learned about Scala Type Inference . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Type Parameterization.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.