class A {
def a(): Unit = ()
def b[T](f: A => T): T = f(new A())
def c(): Unit = b { _.a() }
def d(): Boolean = b { w => w.a(); true }
//def e(): Boolean = b { _.a(); true } // does not compile - why not, if c compiles?
}
在上面类的 e() 方法中,我认为编译器能够像在 c() 中一样推断出“_”的类型。然而,在 scala 2.11.7 中,e() 会导致“扩展函数缺少参数类型。为什么?这是编译器应该能够做到的事情(=编译器错误)还是编译器的提示正确?
最佳答案
我认为这是因为b { _.a(); true }
get 被编译器翻译成 b { w => { w.a() }; true }
,而不是预期的 b { w => { w.a();真 } }
。因此,它计算整个表达式,并尝试将 Boolean
类型的表达式传递给 b
而不是 A => Boolean
。至少这是我看到的唯一解释,不幸的是我不知道如何检查。编译器的错误似乎很诚实地试图表达这一点。
总体而言,您不应在复杂表达式中使用 _
通配符。它们仅为简单的设计
我也认为 @Felix 对你的问题的评论也是正确的 - 部分这也是问题所在。编译器有歧义:T
可以是Unit
或Boolean
,它只是错误地解决了它。不幸的是,即使您定义 b
来接受 A => Boolean
附注我所说的正确的编译器消息是指这个:
Error:(24, 36) type mismatch;
found : Boolean(true)
required: Main.A => Boolean
def e(): Boolean = bb { _.a(); true } // does not compile - why not, if c compiles?
^
关于scala - 扩展函数缺少参数类型 - 它取决于什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341053/