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 O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.