Scala中部分应用的函数 [英] Partially applied functions in Scala
本文介绍了Scala中部分应用的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想知道是否可以解释以下两种情况的行为为何不同:
Wondering if you can comment on why following two scenarios behave differently:
以下作品:
var la= List(12, 13 , 14 ,15);
var func = (x:Int) => println(x)
la.foreach(func) // 1
la.foreach(func(_)) // 2
但是以下内容却没有:
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
错误:类型不匹配; 找到:单位 必需:Int =>? la.foreach(println(func1(_)))
error: type mismatch; found : Unit required: Int => ? la.foreach(println(func1(_)))
推荐答案
这种情况已经废止了
la.foreach(println(func1(_)))
到
la.foreach(println(x => func1(x)))
因此您将函数传递给println
,打印返回类型为Unit,foreach需要一些Int => ?
函数.
So you passing the function to println
, print return type is Unit and foreach requires some Int => ?
function.
相比之下,两种情况下的第一个样本都用Int => Unit
喂foreach
,而两种情况下的第二种样本都用Unit
喂foreach
.
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
.
这篇关于Scala中部分应用的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文