1
votes

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?

1
When you write def f[Unit,Int](x: Unit), you're declaring a generic method with two type parameters Unit and Int that shadow the builtin types of the same name.Chris Martin

1 Answers

2
votes

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
}