[英]What is the meaning of the chaining of => (rightward double arrow) operator in Scala's function literal?
What is the meaning of chaining of =>
operator like in this code: 像这样的代码中
=>
运算符的链接是什么意思:
val a = Array("I", "love", "Scala Johnson")
a.foreach {
x => y: String => println(x)
}
It printed out nothing. 它什么也没打印出来。
So what happened? 所以发生了什么事? Does the
x
lost in compilation? x
是否在编译中丢失?
If I removed String
type declaration from y
parameter: 如果我从
y
参数中删除了String
类型声明:
x => y => println(x)
I got "missing parameter type"
compile error. 我收到
"missing parameter type"
编译错误。
Then I did an experiment: 然后我做了一个实验:
val hotFunc: Int => Int => Unit = x => y => println(x * y)
hotFunc(2)(11)
It printed out 22
. 它打印了
22
。
So, does the chaining of =>
mean currying? 那么,
=>
的链接是否意味着currying?
UPDATE: 更新:
The 3rd case: 第三种情况:
def readFile[T](f: File)(handler: FileInputStream => T): T = {
val resource = new java.io.FileInputStream(f)
try {
handler(resource)
} finally {
resource.close()
}
}
val bs = new Array[Byte](4)
readFile(new File("Slurp.scala")) {
input => b: Byte => println("Read: " + (input.read(bs) + b))
}
It's same with 1st example, printed out nothing. 与第一个示例相同,什么也不打印。
The =>
is right associative, so in your first example you are calling a function with the values of a
, which return a function String=>Unit
(but that never get caught, get converted implicitly to Unit
because of foreach
). 该
=>
是右结合的,所以在你的第一个例子中,你正在呼吁与值的函数a
,它会返回一个函数String=>Unit
(但从来没有被抓住,获得隐式转换为Unit
,因为foreach
)。 Probably it would be more clear with parentheses: 用括号可能会更清楚:
x => ((y: String) => println(x))
which turned to 变成了
x => ((y: String) => println(x); ())
in foreach
, because it expects T => Unit
. 在
foreach
,因为它期望T => Unit
。
Chaining of =>
(without parentheses) is kind of currying, yes. =>
(不带括号)的链接有点麻烦,是的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.