问题描述
在Scala中的Map
上下文中,符号->
是什么意思?
What does the symbol ->
mean in the context of a Map
in Scala?
Scala的Predef
类提供了一种隐式转换,允许一次写入key -> value
作为对(key, value)
的替代语法.我在ScalaByExample中阅读了此书,但看不到它如何用于Maps.
Scala’s Predef
class offers an implicit conversion that lets one writekey -> value
as an alternate syntax for the pair (key, value)
.I read it in ScalaByExample but fail to see how this works for Maps.
推荐答案
->
运算符是在地图上下文中使用时将键与值相关联的简写.在某些语言中,只允许您将键和值对(通常是键在第一个位置,值在第二个位置)传递给构造函数或地图上的各种方法之一,它将被处理适当-Scala映射也允许这样做.
The ->
operator is a shorthand for associating a key with a value when used in the context of a map. In some languages, you are simply allowed to pass the pair of the key and value (usually with the key in the first position and the value in the second) to the constructor or one of the various methods on a map and it will be handled appropriately -- this is also allowed with Scala maps.
,Scala还提供了key -> value
的简写形式,正如您所发现的那样,它在Predef中是通过隐式定义的,以使关联更加清晰.本质上来说,这是在说:拿左边的项目并将其映射到右边的项目."您会注意到,如果您阅读Map对象的定义,它没有定义任何明显使用此->
方法的方法.相反,这些方法采用Tuple2
类型的对象(这是2个值的元组:例如(item1, item2)
),Scala会通过Predef中的方法隐式转换这些对象.
However, Scala also provides the shorthand form of key -> value
, which, as you've discovered, is defined in Predef via an implicit, to make the association more clear. Essentially it's saying: "take the item on the left and map it to the item on the right." You'll notice if you read the definition of the Map object, that it does not define any methods that obviously use this ->
method. Instead, the methods take objects of type Tuple2
(this is a tuple of 2 values: e.g. (item1, item2)
), which Scala implicity converts via the method in Predef.
在某些语言中,->
语法被定义为语言本身的一部分,但是由于Scala的灵活性,因此可以将其简单地定义为方法.
In some languages, the ->
syntax is defined as part of the language itself, but due to the flexibility of Scala, this is able to be defined simply as a method.
这篇关于Scala地图->操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!