Strange things with curry

I have such a strange situation that I do not understand. I read the book Scala Programming, chap. nine.

Say I have a curric function:

def withThis(n:Int)(op:Int=>Unit){ println("Before") op(n); println("After") } 

When I call it with one argument inside the special curly syntax, it works as expected:

 withThis(5){ (x) => {println("Hello!"); println(x); } } // Outputs Before Hello! 5 After 

However, if I put two operators, I get something strange:

 withThis(5){ println("Hello!") println(_) } // Outputs Hello! Before 5 After 

How come "Hello!" is printed before "Before" and then "5" is printed inside? I've gone crazy?

+7
source share
2 answers

Your last code example should be rewritten as follows to get the expected result:

 withThis(5) { x => println("Hello!") println(x) } 

Otherwise your example is equivalent

 withThis(5) { println("Hello!") (x: Int) => println(x) } 

as the _ placeholder will expand to associate the maximum possible with a non-degenerate image (i.e. it will not expand to println(x => x) ).

Another thing is that a block always returns its last value. In your example, the last value is actually (x: Int) => println(x) .

+10
source

In your second example, the part in curlies: { println("Hello!"); println(_) } { println("Hello!"); println(_) } is the block that prints "Hello!" and returns curried println . Imagine being simplified like { println("Hello!"); 5 } { println("Hello!"); 5 } , a block that prints "Hello!" and returns 5.

+3
source

All Articles