Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 875
Michael Avatar asked Dec 25 '22 21:12

Michael


1 Answers

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 }
like image 130
Michael Zajac Avatar answered Jan 05 '23 00:01

Michael Zajac