The Scala compiler often infers the type of variable provided, so we do not have to declare it explicitly. With type inference capabilities, developers can save time writing code that the compiler already knows.
Here is how we declare an immutable variable in Scala:
val variable_name : Scala_data_type = value
With type inference, we can omit the data type. In the following code, the compiler infers that streetName
is a String:
val streetName = "Mansfield Street"println(streetName)
Similar to variables, type inference works with functions as well. Here is how we declare a function in Scala:
def functionName ([parameterList]) : [returnType] = {
// function body
}
def squareOf(x: Int) = x * xprintln(squareOf(4))
In the code above, we omitted the return type in the function. The compiler can infer that the return type is Int
.
However, the compiler cannot infer the return type in recursive functions. Here is a program where we omit the return type, but the compiler will fail. As demonstrated by the error, the method fac
needs an explicit return type:
def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1)
Moreover, we can also omit type parameters when polymorphic methods are called or generic classes are instantiated. In the following program, the compiler uses the type of the argument of ok
to figure out the type of x
. So in line 2, it infers that the type of x
is Int
, and in line 3, it is String
:
def ok[T](x: T) = println(x)ok(1)ok("Hello")
Free Resources