Wednesday, 15 January 2014

Scala: when to use explicit type annotations -



Scala: when to use explicit type annotations -

i've been reading lot of other people's scala code recently, , 1 of things have difficultly (coming java) lack of explicit type annotations.

it's convenient when writing code able leave out type annotations -- when reading code find explicit type annotations help me understand @ glance code doing more easily.

the scala style guide (http://docs.scala-lang.org/style/types.html) doesn't seem provide definitive guidance on this, stating:

use type inference possible, set clarity first, , favour explicitness in public apis.

to mind, bit contradictory. while it's obvious type variable is:

val tokens = new hashmap[string, int]

it's not obvious type 1 is:

val tokens = readtokens()

so, if putting clarity first annotate variables type not declared on same line.

do scala practitioners have guidance on this? crazy considering adding type annotations local variables? i'm particularly interested in hearing folks spend lot of time reading scala code (for example, in code reviews), writing it.

it's not obvious type 1 is:

val tokens = readtokens()

good names important: name plural, ergo returns collection of kind. general collection types in scala traversable , iterator, , share mutual interface, it's not of import 1 of 2 is. name talks "reading tokens", ergo should homecoming tokens in fashion. , lastly not least, method phone call has parentheses, according style guide means has side-effects, wouldn't count on beingness able traverse collection more once.

ergo, homecoming type

traversable[token]

or

iterator[token]

and of 2 doesn't matter because client interfaces identical.

note latter constraint (only traversing collection once) isn't captured in type, if were providing explicit type, still have @ name , style!

scala types

No comments:

Post a Comment