Type Inference

Like any statically typed language, Scala verifies types of objects at compile time. At the same time, it does not require you to state the obvious; it can infer types. You can use type inference for both simple types and generics.

Type Inference for Simple Types

We’ll first explore type inference for simple types. Let’s start with a piece of code where we indicate the type, as we’re used to doing in languages like C++ and Java:

MakingUseOfTypes/DefiningVariableWithType.scala
 
val​ greet : ​String​ = ​"Ahoy!"

We defined a variable named greet, mentioned its type is String, and gave it a value. Unlike Java, where you specify the type and then the variable name, in Scala you do the reverse—for two reasons: First, by asking us to ...

Get Pragmatic Scala now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.