Scala Lesson 29 – Type Inference | Dataplexa

Type Inference

In this lesson, you will learn about Type Inference in Scala. Type inference allows the Scala compiler to automatically determine the data type of a variable or expression.

This feature helps you write cleaner, shorter, and more readable code without losing type safety.


What Is Type Inference?

Type inference means that you do not always need to explicitly specify the type of a variable.

Scala analyzes the assigned value and infers the correct type at compile time.


Basic Type Inference Example

In the example below, Scala infers the type automatically.

val number = 10
val name = "Scala"
val isActive = true

Here:

  • number is inferred as Int
  • name is inferred as String
  • isActive is inferred as Boolean

Explicit vs Inferred Types

You can still explicitly specify types if needed.

val count: Int = 5
val message: String = "Hello"

Both explicit and inferred styles are valid. Scala developers usually prefer type inference when the code is clear.


Type Inference in Expressions

Scala can infer types from expressions and operations.

val sum = 10 + 20
val result = if (sum > 20) "Large" else "Small"

In this example:

  • sum is inferred as Int
  • result is inferred as String

Type Inference in Functions

Scala can infer the return type of functions.

def add(a: Int, b: Int) = {
  a + b
}

The compiler infers the return type as Int.

However, for public APIs and complex methods, explicitly specifying the return type is considered a best practice.


Type Inference with Collections

Collections heavily rely on type inference.

val numbers = List(1, 2, 3, 4)
val names = List("Alice", "Bob", "Charlie")

Scala infers the element types automatically.


Limitations of Type Inference

Type inference is powerful but not unlimited.

In some cases, Scala cannot infer the type clearly, and you must specify it.

val data: List[Any] = List(1, "Scala", true)

Explicit typing avoids ambiguity and improves readability.


Why Type Inference Matters

  • Reduces boilerplate code
  • Improves readability
  • Maintains strong type safety
  • Speeds up development

📝 Practice Exercises


Exercise 1

Create three variables without specifying types and let Scala infer them.

Exercise 2

Write a function where the return type is inferred.

Exercise 3

Create a list and let Scala infer its element type.


✅ Practice Answers


Answer 1

val age = 25
val language = "Scala"
val active = false

Answer 2

def multiply(x: Int, y: Int) = x * y

Answer 3

val values = List(10, 20, 30)

What’s Next?

In the next lesson, you will learn about Companion Objects and how Scala uses them to group related logic together.