简体   繁体   English

了解Scala->语法

[英]Understanding Scala -> syntax

I am getting a taste of Scala through the artima " Programming in Scala " book. 通过artima“ Scala编程 ”一书,我对Scala有所了解。

While presenting the Map traits, the authors go to some lengths to describe the -> syntax as a method that can be applied to any type to get a tuple. 在介绍Map特征时,作者竭尽全力将->语法描述为一种可应用于任何类型以获取元组的方法。

And indeed: 确实:

scala> (2->"two")
res1: (Int, String) = (2,two)

scala> (2,"two")
res2: (Int, String) = (2,two)

scala> (2->"two") == (2, "two")
res3: Boolean = true

But those are not equivalent: 但是这些并不等效:

scala> Map(1->"one") + (2->"two")
res4: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)

scala> Map(1->"one") + (2, "two")
<console>:8: error: type mismatch; 
found   : Int(2)
required: (Int, ?)
             Map(1->"one") + (2, "two")

Why is this so, since my first tests seem to show that both "pair" syntaxes build a tuple? 为什么会这样,因为我的第一个测试似乎表明两个“ pair”语法都构成一个元组?

Regards. 问候。

They are exactly the same, thanks to this class in Predef (only partly reproduced here): 由于Predef中的Predef ,它们完全相同(此处仅部分复制):

final class ArrowAssoc[A](val __leftOfArrow: A) extends AnyVal {
  @inline def -> [B](y: B): Tuple2[A, B] = Tuple2(__leftOfArrow, y)
}
@inline implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)

So now the question is when will (a,b) syntax be ambiguous where (a -> b) is not? 因此,现在的问题是, (a,b)语法何时不明确,而(a -> b) a- (a -> b)不在哪里? And the answer is in function calls, especially when they're overloaded: 答案就在函数调用中,尤其是当它们重载时:

def f[A](a: A) = a.toString
def f[A,B](a: A, b: B) = a.hashCode + b.hashCode
f(1,2)     // Int = 3
f(1 -> 2)  // String = (1,2)
f((1, 2))  // String = (1,2)

Map + in particular gets confused because it's overloaded with a multiple-argument version, so you could 尤其是Map +感到困惑,因为它已被多参数版本重载,因此您可以

Map(1 -> 2) + (3 -> 4, 4 -> 5, 5 -> 6)

and it thus interprets 因此它解释

Map(1 -> 2) + (3, 4)

as trying to add both 3 to the map, and then 4 to the map. 尝试将34到地图上。 Which of course makes no sense, but it doesn't try the other interpretation. 哪一个当然没有意义,但它不会尝试其他解释。

With -> there is no such ambiguity. 使用->不会有这种歧义。

However, you can't 但是,你不能

Map(1 -> 2) + 3 -> 4

because + and - have the same precedence. 因为+-具有相同的优先级。 Thus it is interpreted as 因此,它被解释为

(Map(1 -> 2) + 3) -> 4

which again fails because you're trying to add 3 in place of a key-value pair. 再次失败,因为您尝试将3代替键值对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM