首页 文章

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

提问于
浏览
1

在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"产生一个"type mismatch: found Boolean, required Nothing" . 如果我将 ??? 替换为true或false,则编译 . 如果我在抽象类中指定"method"的结果类型,它也会编译 .

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

2 回答

  • 3

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

    abstract class A {
        def foo: Any
    }
    
    abstract class B {
        def foo: Int
    }
    
    new B {
        def foo = 1
    }
    

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

  • 6

    返回类型 def method(a: Int) = ??? 实际上是 Nothing .

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

    现在,类 B 中的 method 正在覆盖父特征的 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 = ???
    }
    

相关问题