Michael
Michael

Reputation: 42050

How to fix this 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 am wondering what it exactly means and how to fix it.

Upvotes: 4

Views: 1082

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

You probably don't need that type parameter on the method foo. The problem is that it's shadowing the type parameter of it's trait Foo, but it's not the same.

 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 }

Upvotes: 10

Related Questions