开发者

Question on curried Function

Just wanted to know question w.r.t Currying

If we have defined the curried function curriedNewSum

scala> def curriedNewSum(x : Int)(y : Int) = x + y
curriedNewSum: (x: Int)(y: Int)Int

scala> curriedNewSum(10)(20)
res5: Int = 30

scala> var tenPlus = curriedNewSum(10)_
tenPlus: (Int) => Int = <function1>

scala> tenPlus(20)
res6: Int = 30

scala> var plusTen = curriedNewSum(_)(20)
<console>:6: error: missing parameter typ开发者_开发技巧e for expanded function ((x$1) => curri
edNewSum(x$1)(20))
       var plusTen = curriedNewSum(_)(20)
                                   ^

So why does curriedNewSum(10)_ works & curriedNewSum(_)(10) not?


I'm not 100% sure what exactly is the problem, but I strongly suspect this isn't doing what you think it is.

Try, for instance,

var plusTen = curriedNewSum(_)

You'll see it will return a Function1[Int, Function1[Int, Int]]. Now try this:

var plusTen = (curriedNewSum(_))(10)

And see it work! Well, that translates into:

var plusTen = ((x: Int) => curriedNewSum(x))(10)

While the other way translates into:

var plusTen = (x) => curriedNewSum(x)(10)

Something about how the function is expanding is screwing up with the type inference.


I am not exactly sure why it doesn't work. But this seems to work:

curriedNewSum(_:Int)(20)

After I thought about this more, it might be that the possibility exists of having an overloaded curriedNewSum methods

curriedNewSum(x:Double)(y:Int)
curriedNewSum(x:Float)(y:Int)

which one would be chosen? Defining the type explicitly says which method you want.


I suspect the type should be inferred where there is no ambiguity and that this is a bug or deliberately omitted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜