Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What is Type Inference in Scala?

Adnan Abbas

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

Scala compiler inferring type.

Examples

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 * x
println(squareOf(4))
Type inference in functions.

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)
Scala compiler does not infer return type for recursive functions.

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")

RELATED TAGS

scala

CONTRIBUTOR

Adnan Abbas
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring