Scala: when to use explicit type annotations

I've been reading a lot of other Scala code recently, and one of the things I find it hard to do (coming from Java) is the lack of explicit type annotations.

This is certainly handy when writing code to remove type annotations. However, as I read the code, I often find that explicit type annotations help me understand at a glance what makes the code easier.

The Scala Style Guide ( http://docs.scala-lang.org/style/types.html ) doesn't seem to provide any definitive guidelines on this, which says:

Use type inference where possible, but be clear first, and explain the obvious in public APIs.

In my opinion, this is a bit contradictory. Although it is clear what type of this variable is:

val tokens = new HashMap[String, Int]

      

It's not so obvious which type it is:

val tokens = readTokens()

      

So, if this was my first time to clarify, I would probably annotate all variables where the type has not yet been declared on the same line.

Does any Scala practitioner have any guidance on this? Am I crazy to consider adding type annotations to my local variables? I am especially interested in hearing from people who spend a lot of time reading Scala code (for example, in code reviews) as well as writing it down.

+3


source to share


1 answer


It's not so obvious which type it is:

val tokens = readTokens()

      

Good names are important: the name is plural, ergo returns some collection. The most common collection types in Scala are Traversable

and Iterator

, and they mostly share a common interface, so it doesn't matter which one it has. The name also speaks of "reading tokens", ergo should obviously return Token

in some way. Last but not least, the method call has parentheses, which, according to the style guide, means it has side effects, so I won't count on being able to iterate over the collection more than once.

Ergo, the return type is something like

Traversable[Token]

      



or

Iterator[Token]

      

and which of the two it doesn't really matter, as their client interfaces are basically identical.

Note also that the last constraint (only moving the collection once) is not even captured in the type, even if you provide an explicit type, you still have to look up the name and style!

+4


source







All Articles