无法了解Scala函数应用程序中的占位符_行为 [英] Unable to understand placeholder _ behavior in scala function application

查看:65
本文介绍了无法了解Scala函数应用程序中的占位符_行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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>

我不明白为什么函数的占位符(没有建议的类型)应用程序会创建一个带有额外的void参数前缀的新的curried函数.

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.

推荐答案

我想是由于

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.

这篇关于无法了解Scala函数应用程序中的占位符_行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆