O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required