Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

Why does Scala choose to have the types after the variable names?

In Scala variables are declared like:

var stockPrice: Double = 100.

Where the type (Double) follows the identifier (stockPrice). Traditionally in imperative languages such as C, Java, C#, the type name precedes the identifier.

double stock_price = 100.0;

Is it purely a matter of taste, or does having the type name in the end help the compiler in any way? Go also has the same style.

question from:https://stackoverflow.com/questions/6085576/why-does-scala-choose-to-have-the-types-after-the-variable-names

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As well as supporting type inference, this has an ergonomic benefit too.

For any given variable name + type, chances are that the name is the more important piece of information. Moving it to the left makes it more prominent, and the code more readable once you're accustomed to the style.

Other ergonomic benefits:

  • With val, var or def before member names, instead of their type, they all neatly line up in a column.
  • If you change just the type of a member, or drop it entirely in favour of inference, then a fine-grained diff tool will clearly show that the name is unaltered
  • Likewise, changing between a val/var/def is very clear in diffs
  • inference should be considered default behaviour in Scala, you only need type specifications in certain specific scenarios, even then it's mostly done for the compiler. So putting them at the very start of a declaration emphasises the wrong thing.
  • "name: Type" instead of "Type name" more closely matches the way most programmers will actually think about a declaration, it's more natural.
  • The differing C/C++ and Java conventions for pointers and arrays (i.e * being a prefix on the following name and not a suffix on the preceeding type in C/C++, or [] being a valid suffix on both names and types in Java) are still confusing to newcomers or language converts, and cause some very real errors when declaring multiple variables on a single line. Scala leaves no room for doubt and confusion here.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...