We can call type inference a built-in Scala feature that permits us to omit type information while writing code. This means we don't have to specify the type while declaring any variables; Scala compiler can do it for us:
scala> val treatMeAString = "Invisible" treatMeAString: String = Invisible
We did not specify our val
, to be of String
type, but seeing the value of Invisible
, Scala compiler was able to infer its type. Also with some constraints, we can also omit the method's return types:
defcheckMeImaString(x: Boolean) = if(x) "True"else "False"
Here we did not give the return type, as Scala compiler was able to infer its type. But for recursive methods, this doesn't work. The famous factorial method expects you to specify the return type if implementation is recursive:
def recursiveFactorial(n: Int) = if(n == 0) 1 else recursiveFactorial(n-1) //Recursive method recursiveFactorial needs result type
Scala uses a constraints-driven algorithm to implement type inference. It...