Scala - 推断为错误类型,导致类型不匹配?
Scala - inferred as wrong type, leading to type mismatch?
在 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,它会编译。如果我在摘要 class.
中指定 "method" 的结果类型,它也会编译
这不是什么大问题。但是我很好奇是否有人可以解释为什么 ???
没有被正确推断为布尔值?
Scala 允许您使继承方法的 return 类型在子 class 中更具限制性。
abstract class A {
def foo: Any
}
abstract class B {
def foo: Int
}
new B {
def foo = 1
}
所以当你在B
中声明def method(a: Int) = ???
时,???
被推断为Nothing
,因为scala编译器不知道你是否想要Boolean
] 或 Nothing
。这就是为什么显式声明 return 类型总是一个好主意的原因之一。
Return def method(a: Int) = ???
的类型实际上是 Nothing
.
scala> def method(a: Int) = ???
method: (a: Int)Nothing
现在,class 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 = ???
}
在 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,它会编译。如果我在摘要 class.
这不是什么大问题。但是我很好奇是否有人可以解释为什么 ???
没有被正确推断为布尔值?
Scala 允许您使继承方法的 return 类型在子 class 中更具限制性。
abstract class A {
def foo: Any
}
abstract class B {
def foo: Int
}
new B {
def foo = 1
}
所以当你在B
中声明def method(a: Int) = ???
时,???
被推断为Nothing
,因为scala编译器不知道你是否想要Boolean
] 或 Nothing
。这就是为什么显式声明 return 类型总是一个好主意的原因之一。
Return def method(a: Int) = ???
的类型实际上是 Nothing
.
scala> def method(a: Int) = ???
method: (a: Int)Nothing
现在,class 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 = ???
}