Partially applied functions in Scala

人盡茶涼 提交于 2020-01-05 07:52:23

问题


Wondering if you can comment on why following two scenarios behave differently:

The following works:

var la= List(12, 13 , 14 ,15);
var func = (x:Int) => println(x)
la.foreach(func)                   // 1
la.foreach(func(_))                // 2

But the following does not:

var la= List(12, 13 , 14 ,15);
var func1 = (x:Int) => {
    for (i <- 0 to x) yield i*2
 } mkString
la.foreach(println(func1))         // similar to 1 above
la.foreach(println(func1(_)))      // similar to 2 above

error: type mismatch; found : Unit required: Int => ? la.foreach(println(func1(_)))


回答1:


This case is desugared

la.foreach(println(func1(_))) 

to

la.foreach(println(x => func1(x)))

So you passing the function to println, print return type is Unit and foreach requires some Int => ? function.

In contrasting, the first sample in both cases you are feeding foreach with Int => Unit, while in the 2nd sample in both cases you are feeding foreach with Unit.




回答2:


In the second code snippet, you're calling println with a function as its argument and then trying to pass the result of that call as an argument to foreach. Since println does not return a function, but foreach wants one, that does not work.



来源:https://stackoverflow.com/questions/13518677/partially-applied-functions-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!