tags:

views:

180

answers:

4

I am reading Scala and I am wondering ...
Why

val capacity : Int

instead of

val Int capacity.

Any reason why this choice was made. If not, it does not seem to me like a good choice to move away from the Java way of declaring it. Would have made the transition from Java to Scala easier (not by much, but little bit)

+11  A: 

Because the majority of the time you can leave off the Int part. Scala has a much neater system of type inference than Java does.

Wysawyg
If you add an example with and without the type it will make more obvious the reason.
Daniel
+4  A: 

x : T is the standard notation for types in logic and many programming languages. C and its descendants, with Java among them, deviates from this. But the type notation of C is really awful (try to write down the type for some moderately complicated higher order function like map).

Also, with this notation it is easy to leave out the type (as Wysawyg has already written), or to add a type inside an expression.

starblue
+1  A: 

Here's an example to Wysawyg's statement:

val capacity = 2

But you typically might not do this with just a val.

trait Foo {
  def capacity = 2 // A default value
}

// Force instances of Bar to set the value
class Bar( override val capacity : Int ) extends Foo

(I tried to insert this as a comment, but alas, no formatting.)

Tristan Juricek
+1  A: 

In Programming in Scala it says the technical reason for this syntax is it makes the type inference easier.

Fabian Steeg