scala - 扩展函数缺少参数类型 - 它取决于什么?

标签 scala types

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可以是UnitBoolean,它只是错误地解决了它。不幸的是,即使您定义 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/

相关文章:

scala - 部署没有依赖项的 Scala 二进制文件

scala - Spark Scala : retrieve the schema and store it

scala - SBT:将哪些文件置于版本控制之下?

c# - 无法推断 C# 中的类型,必须明确设置吗?

ios - 无法将类型的值转换为预期的参数类型 NSURLSessionDelegate

scala - 在 Scala 中使用隐式的良好实践

scala - 将函数应用于列表列表内的元素

sql-server-2008 - Entity Framework SQL 异常 : The supplied value is not a valid instance of data type float

c# - 如何将对象转换为 Type 类描述的类型?

C header 和未声明变量中的类型冲突?