3
votes

I have a problem with generics in Scala. I have two classes

import scala.reflect.ClassTag

class Data[T: ClassTag](val list: List[T]) {

}

trait Transformation {
  def transform[T, U](data: Data[T]) : Data[U]
}

Now I want to implement a class to pass from Int to String, something like this

class FromInt2String extends Transformation {
  override def transform[String, Int](data: Data[String]) = ???
}

But I know this is exactly like

class FromInt2String extends Transformation {
  override def transform[T, U](data: Data[T]) = ???
}

How can I do this without adding type parameters in the Transformation?

Thanks

1

1 Answers

4
votes

How can I do this without adding type parameters in the Transformation?

If you don't want generic type parameters, you can use Abstract Types:

trait Transformation {
  type T
  type U

  def transform(data: Data[T]) : Data[U]
}

class FromInt2String extends Transformation {
  override type T = String
  override type U = Int

  override def transform(data: Data[String]): Data[Int] = ???
}