我正在阅读一些Scala代码。 ->
在以下背景下意味着什么?
var queries = { "Select apple from farm" -> None, "Select orange from fram" -> None, "Select blueberry from anotherFarm" -> Some( #randomStuff ) }
它看起来像一个lambda函数列表,但我认为在那种情况下应该是=>
而不是->
。
此外,这个单行代码是什么意思?
def onConnection(id) = { application ! turnOnApplication(id) }
具体来说,我对使用!
感到困惑。它似乎不像大多数语言中那样“不”
->
符号是在Scala中定义tuple的一种方法。以下都是等价的:
val apples1 = "Select apple from farm" -> None
val apples2 = ("Select apple from farm" -> None)
val apples3 = ("Select apple from farm", None)
至于!
:
def onConnection(id) = { application ! turnOnApplication(id) }
Scala中的!
可以是negation运算符,但上面代码片段中的!
看起来像tell
的Akka(Akka是Scala的主要演员库)。此模式用于向actor发送消息。因此,如果application
是对actor的引用,则代码片段会将turnOnApplication(id)
的结果发送给application
actor。从链接的文档:
“!”意思是“即发即忘”,例如异步发送消息并立即返回。也称为告诉。
细箭头->
是元组语法。这只是编写元组的另一种方式。即
val x: (Int, String) = 3 -> "abc"
与写作相同:
val x: (Int, String) = (3, "abc")
箭头语法通过提供隐式类ArrowAssoc
来完成,该类定义了方法def ->[B](y: B): (A, B)
。 ArrowAssoc
是Predef
的一部分,它插入到每个Scala源文件中。你可以找到文件here.
括号语法同时是编译器完成的语法糖。
您可以使用两种语法形成元组
1)使用逗号
val tuple = (1, 2)
2)使用->
(箭头)
val tuple = 1 -> 2
Repl规模
scala> val tuple = (1, 2)
tuple: (Int, Int) = (1,2)
scala> val tuple = 1 -> 2
tuple: (Int, Int) = (1,2)
Finding-symbols将->
定义为Method provided by implicit conversion
。只需看看用implicit
标记的方法,它接收作为参数的接收方法的类型的对象。例如:
"a" -> 1 // Look for an implicit from String, AnyRef, Any or type parameter
在上面的例子中,->
在类ArrowAssoc中通过any2ArrowAssoc
方法定义,该方法采用A
类型的对象,其中A
是同一方法的无界类型参数。
qazxsw poi将qazxsw poi定义为qazxsw poi