如何修复 Scala 中的这种类型不匹配错误?
How to fix this type mismatch error in Scala?
我在 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 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 }