2015-03-31 79 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