Summary: A discussion of Scala type annotations and type ascription.
While Scala normally determines the type you want to use automatically, such as this Int:
scala> val x = 1 x: Int = 1
there may be times you want to control the type, such as if you want a Byte, Short, Long, Double, Float, etc. In these cases you can annotate your type when you create it, like this:
scala> val a:Byte = 0 a: Byte = 0 scala> val a:Int = 0 a: Int = 0 scala> val a:Short = 0 a: Short = 0 scala> val a:Double = 0 a: Double = 0.0 scala> val a:Float = 0 a: Float = 0.0
While I tend to use that form, I believe the preferred approach is to put the type after the value, like this:
scala> val a = 0: Byte a: Byte = 0 scala> val a = 0: Double a: Double = 0.0
(See the annotations section of the Scala Style Guide, which briefly refers to this style.)
Again, the need for type annotation in Scala is not common; the compiler normally determines the type you need correctly, as shown in the first example. But if you need to override the type that the Scala compiler will assign, type annotation can be your solution.
Scala type ascription
Scala type ascription is a slightly different beast, and can easily be confused with type annotation. As the official Scala documentation states, "Type ascription is often confused with type annotation, as the syntax in Scala is identical."
Honestly, I'm not 100% certain that I understand the differences between type annotation and type ascription, but in the examples I've seen, type ascription is typically an up-casting of a type (while annotation is more about clearly specifying which type you want as the result of an expression). As the official docs state, "Ascription is basically just an up-cast performed at compile-time for the sake of the type checker." They share these examples of type ascription:
Nil: List[String] Set(values: _*) "Daniel": AnyRef
On Stack Overflow, Daniel Sobral shares an example of type ascription that begins like this:
scala> val s = "Dave" s: java.lang.String = Dave scala> val p = s: Object p: java.lang.Object = Dave
In this case he's explicitly declaring that he wants the variable p
to be an Object
, and not a String
.
If I ever have a need for this feature I'll be glad to include more examples, but until then, if you needed to see some examples of Scala type annotation and ascription, I hope this was helpful.
As usual, if you have any corrections or improvements to these notes, please leave a note in the Comments section below.