Scala - 推断为错误类型,导致类型不匹配?

时间:2015-02-27 19:47:31

标签: scala inheritance types

在Scala 2.11.5中,编译此

object Tryout {
  trait A {
    def method(a: Int): Boolean
  }

  abstract class B extends A {
    def method(a: Int) = ???
  }

  new B {
    override def method(a: Int) = true  // type mismatch here
  }
}

在“true”处产生“类型不匹配:找到布尔值,需要无效”。如果我将???替换为true或false,则会编译。如果我在抽象类中指定结果类型“method”,它也会编译。

这不是一个大问题。但是我很好奇是否有人可以解释为什么???没有被正确推断为布尔值?

2 个答案:

答案 0 :(得分:6)

Scala允许您在子类中使继承方法的返回类型更具限制性。

abstract class A {
    def foo: Any
}

abstract class B {
    def foo: Int
}

new B {
    def foo = 1
}

因此,当您在def method(a: Int) = ???中声明B时,???被推断为Nothing,因为scala编译器不知道您是否需要Boolean }或Nothing。这是明确声明返回类型总是一个好主意的原因之一。

答案 1 :(得分:3)

def method(a: Int) = ???的返回类型实际为Nothing

scala> def method(a: Int) = ???
method: (a: Int)Nothing

现在,班级method中的B会覆盖父级特征的method。您应该像这样定义您的claas B,

abstract class B extends A {
  // def method is provided by trait A
}

abstract class B extends A {
  // def method with full signature
  override def method(a: Int): Boolean = ???
}