2015-03-31 82 views
3

我在斯卡拉REPL以下错误:如何修复Scala中的这种类型不匹配错误?

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 } 
               ^

我想知道它到底意味着,以及如何解决它。

回答

9

您可能不需要方法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 } 
+0

谢谢。有用! – Michael 2015-03-31 14:33:59

+0

噢,是的。忘了去做吧。抱歉。 – Michael 2015-04-01 13:29:35