3

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 Answer 1

4

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] = ???
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.