Unable to understand placeholder _ behavior in scala function application

╄→尐↘猪︶ㄣ 提交于 2020-01-05 03:06:29

问题


Welcome to Scala version 2.10.2
Type in expressions to have them evaluated.
Type :help for more information.

scala> val fn = (x:Int) => x+1
fn: Int => Int = <function1>

scala> val fn1 = fn _
fn1: () => Int => Int = <function0>

scala> val fn2 = fn1 _
fn2: () => () => Int => Int = <function0>

I don't understand why the placeholder(without a suggested type) application to a function is creating a new curried function with prefixed additional void argument.

I was expecting a compiler error or at least a warning.


回答1:


I guess it's so due to the uniform access principle: in REPL val is a field of object, not a local variable. And all not private[this] fields are getter methods.

So your code is something like this:

def fn() = (x:Int) => x+1
val fn1 = fn _ // () => fn()

It works as expected with local variables:

scala> {
     |   val fn = (x:Int) => x+1
     |   val fn1 = fn _
     | }
<console>:10: error: _ must follow method; cannot follow Int => Int
                val fn1 = fn _
                          ^

Even though I can explain why it works this way, I still think this behavior can be considered a error.



来源:https://stackoverflow.com/questions/17484457/unable-to-understand-placeholder-behavior-in-scala-function-application

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