问题
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)
回答1:
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.
回答2:
I think I read a statement by Martin Odersky himself somewhere saying that this decision was also made in order to improve readability. This is certainly the case, e.g. compare
val Double number = ...
val Array[(Seq[String], Map[Seq[String], Double])] something = ...
val String pattern = ...
with
val number : Double = ...
val something : Array[(Seq[String], Map[Seq[String], Double])] = ...
val pattern : String = ...
Most of the time you need to find names of references/mathods fast (visually), not types.
回答3:
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.
回答4:
In Programming in Scala it says the technical reason for this syntax is it makes the type inference easier.
回答5:
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 // Allow child classes to override and decide the value later
}
// Force instances of Bar to set the value
class Bar( override val capacity : Int ) extends Foo
// Have Bat determine it on the fly
trait Bat extends Foo {
def onlyAThird : Int
override def capacity = onlyAThird * 3
}
(I tried to insert this as a comment, but alas, no formatting.)
回答6:
I think Daniel thought of something like that:
val a = 7
val b: Int = 8
var x = "Foo"
var y: String = "Bar"
def sum (a: Int, b: Int) = a + b
def mul (a: Int, b: Int): Int = a * b
The type can often be inferred.
来源:https://stackoverflow.com/questions/1891775/any-reason-for-having-val-capacity-int-instead-of-val-int-capacity-in-scal