Scala Language Type Inference Local Type Inference


Example

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