Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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.

like image 869
Rohit Avatar asked May 22 '11 01:05

Rohit


People also ask

What is the default type of a Scala variable?

By contrast, Scala has two types of variables: val creates an immutable variable (like final in Java) var creates a mutable variable.

What are the two types of variables in the scripting?

Variables in Shell Scripting: The variables are of two types of user-defined variables and system-defined variables.

Which type of variable has permanent value throughout the Scala?

Immutable variables are that variable which value cannot be changed once it is created and is declared using 'val' keyword.


1 Answers

Kevin's got it right. The main observation is that the "type name" syntax works great as long as types are short keywords such as int or float:

int x = 1 float d = 0.0 

For the price of one you get two pieces of information: "A new definition starts here", and "here's the (result) type of the definition". But we are way past the area of simple primitive types nowadays. If you write

HashMap<Shape, Pair<String, String>> shapeInfo = makeInfo() 

the most important part of what you define (the name) is buried behind the type expression. Compare with

val shapeInfo: HashMap[Shape, (String, String)] = makeInfo() 

It says clearly

  • We define a value here, not a variable or method (val)
  • The name of the thing we define is shapeInfo
  • If you care about it, here's the type (HashMap[...])
like image 190
Martin Odersky Avatar answered Oct 11 '22 22:10

Martin Odersky