mardi 4 janvier 2022

How to call a parametriezed method having implicit argument using reflection in Scala?

Suppose there is a typical type class

trait Gen[T] {
  def generate(): T
}

object Gen {
  val random = new Random()

  implicit val stringGen: Gen[String] = () => random.nextString(10)
  implicit val intGen: Gen[Int] = () => random.nextInt()

  implicit def optionGen[T: Gen]: Gen[Option[T]] = () => Some(implicitly[Gen[T]].generate())
}

object Generator {
  def apply[T: Gen]: T = implicitly[Gen[T]].generate()
}

Calling Generator[Option[String]] will generate a random string wrapped in a Some.

How can Generator.apply be called at runtime via reflection having for example as parameter a type like val typeTag = typeOf[Option[String]]?





Aucun commentaire:

Enregistrer un commentaire