What is Type inference in Scala

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-26 23:37:37 Viewed : 283


What is Type inference in Scala:

Type inference in Scala refers to the ability of the compiler to automatically deduce and assign data types to variables, expressions, and function return values without requiring explicit type annotations. Scalas type inference system makes the language concise while ensuring type safety. Here are some examples to illustrate type inference in Scala:

1. Basic Variable Declaration:

scala
val number = 42

In this example, the type of the variable number is inferred as Int because the value 42 is an integer literal.

2. Function Return Types:

scala
def add(x: Int, y: Int) = x + y

In this function, the return type is inferred as Int because the + operator operates on integers, so the result must be an integer.

3. Collections and Type Inference:

Scalas collections use type inference extensively. For example, when creating a List, you dont need to specify the type:

scala
val numbers = List(1, 2, 3, 4, 5)

In this case, the type of numbers is inferred as List[Int] because all elements are integers.

4. Option Type:

The Option type is often used in Scala for handling optional values. Type inference works well with Option:

scala
val maybeValue: Option[String] = Some("Hello, Scala!")

Here, the type Option[String] is inferred based on the type of the value passed to Some.

5. Pattern Matching:

Type inference also works when pattern matching. For instance:

scala
val result = "Hello" match { case "Goodbye" => 0 case s: String => s.length }

In this example, result is inferred as an Int because both potential values (0 and the length of a string) are integers.

6. Generic Types:

Scalas type inference extends to generic types as well. For example:

scala
val myList = List(1, 2, 3)

In this case, the type of myList is inferred as List[Int], where Int is the type parameter.

7. Anonymous Functions (Lambdas):

Scalas type inference is useful when defining anonymous functions (lambdas). For example:

scala
val multiply = (x: Int, y: Int) => x * y

The types of x and y are inferred as Int, and the return type of the lambda is also inferred as Int.

Type inference in Scala allows you to write concise and expressive code without sacrificing type safety. It reduces the need for explicit type annotations, making the code more readable and maintainable while still ensuring that the program is type-correct.

Search
Related Articles

Leave a Comment: