[英]How to fix this type mismatch error in Scala?
I got the following error in Scala REPL: 我在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 }
^
I am wondering what it exactly means and how to fix it. 我想知道它究竟意味着什么,以及如何解决它。
You probably don't need that type parameter on the method foo
. 您可能在方法
foo
上不需要该类型参数。 The problem is that it's shadowing the type parameter of it's trait Foo
, but it's not the same. 问题是它影响了它的特性
Foo
的类型参数,但它不一样。
object FooInt extends Foo[Int] {
def foo[Int] = 0
// ^ This is a type parameter named Int, not Int the class.
}
Likewise, 同样,
trait Foo[T] { def foo[T]: T }
^ not the ^
same T
You should simply remove it: 你应该删除它:
trait Foo[T] { def foo: T }
object FooInt extends Foo[Int] { def foo = 0 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.