Trying to get a parametrized function that would return the specified coproduct of a trait.
sealed trait Tr { def x: Int }
case class Cl1(x: Int) extends Tr
case class Cl2(x: Int) extends Tr
def getTr[A <: Tr](i: Int): A = {
???
}
How can this be achieved in Scala 2.11?
You could use a TypeTag for
Aand compare it toCl1andCl2:Note that I had to change the return type to
Tr. It can't work withAbecause the compiler wouldn't allow having branches that resolve into different types forA(we don't know the actualA, but it surely can't be bothCl1andCl2at the same time). Side note: GADTs actually have a bit of special treatment by the compiler which allows such cases, e.g.:By the way, is your question a contrived example or a real scenario? If it's the latter, I feel it should be possible to implement it in a more elegant way.