简体   繁体   中英

How to instantiate generic function from a trait in Scala?

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 (ie 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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM