简体   繁体   中英

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?

If I removed String type declaration from y parameter:

x => y => println(x)

I got "missing parameter type" compile error.

Then I did an experiment:

val hotFunc: Int => Int => Unit = x => y => println(x * y)
hotFunc(2)(11)

It printed out 22 .

So, does the chaining of => mean 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 ). 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 .

Chaining of => (without parentheses) is kind of currying, yes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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