scc
scc

Reputation: 10716

Scala - Instantiate generic type with arguments?

From what I understand if class A and B did not have any arguments then ClassTag could be used here but since they do have arguments, not sure how I could avoid creating 2 methods here, one for SimpleA and another for SimpleB with the same body..

trait Simple {
  val id: UUID
  val name: String
}
case class SimpleA(id: UUID, name: String) extends Simple
case class SimpleB(id: UUID, name: String) extends Simple

def fromTupleToSimple[T <: Simple](sf: (UUID, String)): T = new T(sf._1, sf._2)

Trying to instantiate T gives the error class type required but T found. Not sure how these types of problems are normally solved.

Upvotes: 1

Views: 76

Answers (1)

Dima
Dima

Reputation: 40510

Well, you can still you ClassTag, it just becomes a bit trickier:

def fromTupleToSimple[T <: Simple : ClassTag](sf: (UUID, String)) = classTag
  .runtimeClass
  .getConstructors
  .head
  .newInstance(sf._1, sf._2)
  .asInstanceOf[T]

Upvotes: 2

Related Questions