Reputation: 11
I'm having a weird type mismatch error in Scala when I try to define a class that extends a Trait. I define the following trait
trait T {
def f[A,B](x: A): B
}
And then I define the following class which implements this trait
class A() extends T {
def f[Unit,Int](x: Unit) = {
10
}
}
The idea behind this is that I want to guarantee that any class which has the T trait has a function called "f", regardless of the shape of this function (i.e regardless of its type).
The problem comes when I try to execute the above code, and I get the following error
defined trait T :14: error: type mismatch; found : scala.Int(10) required: Int
So I don't know how am I supposed to specify the type so as to make this work. I have tried to instantiate f as
def f[Unit,scala.Int(10)](x: Unit) = {
10
}
But then the compiler complaints that the type name cannot have '.' . What am I missing?
Upvotes: 1
Views: 276
Reputation: 6353
You can do something like this
trait T[A,B] {
def f(x: A): B
}
class Impl1 extends T[Int, Unit] {
override def f(x: Int): Unit = println(x)
}
class Impl2 extends T[Unit, Int] {
override def f(x: Unit): Int = 10
}
Upvotes: 2