我在 Scala REPL 中遇到以下错误:
scala> trait Foo[T] { def foo[T]:T }
defined trait Foo
scala> object FooInt extends Foo[Int] { def foo[Int] = 0 }
<console>:8: error: type mismatch;
found : scala.Int(0)
required: Int
object FooInt extends Foo[Int] { def foo[Int] = 0 }
^
我想知道它究竟意味着什么以及如何解决它。
最佳答案
您可能不需要该方法的类型参数 foo
.问题是它遮蔽了它的特征 Foo
的类型参数,但不一样。
object FooInt extends Foo[Int] {
def foo[Int] = 0
// ^ This is a type parameter named Int, not Int the class.
}
同样地,
trait Foo[T] { def foo[T]: T }
^ not the ^
same T
你应该简单地删除它:
trait Foo[T] { def foo: T }
object FooInt extends Foo[Int] { def foo = 0 }
关于scala - 如何修复 Scala 中的这种类型不匹配错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29371012/