Here's how type inference works in Scala:
Variable Declarations:
When you declare a variable using the val or var keyword without specifying its type, the compiler infers the type based on the assigned value:
val age = 25 // Compiler infers the type as Int
val name = "Alice" // Compiler infers the type as String
Function Definitions:
When you define functions, the compiler infers the parameter types and return type based on the implementation:
def add(a: Int, b: Int) = a + b // Compiler infers parameter and return types as Int
Expressions:
The result of an expression is inferred based on the types of operands and operations:
val result = 3.14 * 2 // Compiler infers the result type as Double
Type Hierarchy:
Scala's type inference system leverages the type hierarchy to infer the most specific common supertype of the involved expressions:
val myList = List(1, 2, 3) // Compiler infers the type as List[Int]
Type Annotations (Optional):
While type inference is powerful, you can still provide explicit type annotations when necessary for clarity or to guide the compiler:
val x: Double = 42.0
Type inference improves code readability, reduces the likelihood of type-related errors, and promotes a more concise coding style. However, there may be cases where you want to provide explicit type annotations for documentation purposes or when the compiler requires more specific information.