Scala 趣题 15

true or false ?


  class C
  val x1, x2 = new C
  val y1 @ y2 = new C
  println(x1 == x2)
  println(y1 == y2)



























解释

val p1, p2 = new C 是 val p1 = new C; val p2 = new C的简写

val p1@p2 = new C 是一个pattern binder


Explanation


According to the SLS (§4.1), a value definition val p1, . . . , pn : T = e is a shorthand for the sequence of value definitions val p1 : T = e; ...; val pn : T = e. This means that in our example the expression new C is evaluated twice and therefore x1 == x2 is false.


The second value definition is a pattern binder which is defined in SLS §8.1.3. A pattern binder x@p consists of a pattern variable x and a pattern p. In our case the pattern p is a variable pattern which matches any value and binds the variable name (in our case y2) to that value. The pattern binder binds that value also to the pattern variable y1. As the same value is bound to both variables y1 and y2, the expression y1 == y2 is true.


你可能感兴趣的:(scala)