How to fix type mismatch error in Scala?

I got the following error in 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 wonder what exactly this means and how to fix it.

+4
source share
1 answer

You probably don't need this type parameter in a method foo. The problem is that it obscures the parameter type of this attribute foo, but it is not the same.

 object FooInt extends Foo[Int] { 
     def foo[Int] = 0 
          //  ^ This is a type parameter named Int, not Int the class.
 }

Similarly

 trait Foo[T] { def foo[T]: T  }
           ^ not the    ^
              same T

You should simply delete it:

 trait Foo[T] { def foo: T  }
 object FooInt extends Foo[Int] { def foo = 0 }
+10
source

All Articles