Type inference is the feature of a functional programming language that automatically detect the data type of the expression. Scala also supports Type inference in which if a programmer forgot to provide the data type of an expression, that case, Scala compiler will detect the type from the initialization expression.

Omitting the Type of Variable

If we are not defining the type of variable in that case compiler can detect the type of the variable and will project it.

Let us see the below example, we are defining a variable name “businessName” and assigning a value to it. When we run the statement, the compiler automatically detects the type of the variable and prints it on the screen.



Let us see another example, here the compiler detects that it’s an integer data type.



The compiler won’t be able to detect the data type if a recursive method is used.



If we call polymorphic methods generic classes are instantiated in that case we don’t need to mention the type of variable. Scala compiler will infer such missing type parameters from the context and the types of the actual method/constructor parameters.




Method Parameter Types

The compiler doesn’t infer method parameter types. In some cases, it can infer anonymous function parameter types when the function is passed as an argument.




Not to Rely on Type Inference Always

It is more readable to declare the type of variable exposed in a public API. Therefore, it is recommended to make the type explicit for any APIs that will be exposed to users also, the type inference can sometimes infer a too-specific type.

Let us see with the below example.

If we are defining a variable with a null value and if we assigning anyref to that variable, in that case, the compiler will throw a type mismatch error.