...

/

Types

Types

In this lesson, we will go over how to declare types in Scala.

Inference

Use type inference where possible, but put clarity first, and favor explicitness in public APIs.

You should almost never annotate the type of a private field or a local variable, as their type will usually be immediately evident in their value.

Press + to interact
private val name = "Daniel"

Annotations

Type annotations should be patterned according to the following template:

Press + to interact
value: Type

This is the style adopted by most of the Scala standard library. The space between value and type helps the eye in accurately parsing the syntax. The reason to place the colon at the end of the value rather than the beginning of the type is to avoid confusion in cases such as this one:

Press + to interact
value :::

This is actually valid Scala, declaring a value to be of type ::. Obviously, the prefix-style annotation colon muddles things greatly.

Functions

Function types should be declared with a space between the parameter type, the arrow and the return type.

Press + to interact
def foo(f: Int => String) = ...
def bar(f: (Boolean, Double) => List[String]) = ...

Parentheses should be omitted wherever possible.

Structural Types

Structural types should be declared on a single line if they are less than 50 characters in length. Otherwise, they should be split across multiple lines and (usually) assigned to their own type alias.

Press + to interact
// WRONG!
def foo(a: { def bar(a: Int, b: Int): String; val baz: List[String => String] }) = ...
Press + to interact
// RIGHT!
private type FooParam = {
val baz: List[String => String]
def bar(a: Int, b: Int): String
}
def foo(a: FooParam) = ...

Simpler structural types (under 50 characters) may be declared and used inline.

Press + to interact
def foo(a: { val bar: String }) = ...

When declaring structural types inline, each member should be separated by a semi-colon and a single space, the opening brace should be followed by a space while the closing brace should be preceded by a space (as demonstrated in both examples above).