如何在Scala中修复此类型不匹配错误?

Mic*_*ael 4 generics types 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 }
                                                   ^
Run Code Online (Sandbox Code Playgroud)

我想知道它究竟意味着什么,以及如何解决它.

Mic*_*jac 10

您可能不需要该方法的类型参数foo.问题是它影响了它的特征的类型参数Foo,但它不一样.

 object FooInt extends Foo[Int] { 
     def foo[Int] = 0 
          //  ^ This is a type parameter named Int, not Int the class.
 }
Run Code Online (Sandbox Code Playgroud)

同样,

 trait Foo[T] { def foo[T]: T  }
           ^ not the    ^
              same T
Run Code Online (Sandbox Code Playgroud)

你应该删除它:

 trait Foo[T] { def foo: T  }
 object FooInt extends Foo[Int] { def foo = 0 }
Run Code Online (Sandbox Code Playgroud)