scalatraitsscalacheckscala-2.11

Scala generate arbitrary instance of parametrized case class


I'd like to generate an arbitrary element of a parametrized case class, and found this library using ScalaCheck's gen to do it. This works for concrete types, but won't work for abstract ones; is there a way around this?

import com.danielasfregola.randomdatagenerator.RandomDataGenerator._
sealed trait FooBound {
   def bar: String
}

trait Foo[A <: FooBound] {
   implicit val fooBound = random[FooBound] // works fine
   implicit val a = random[A] 
   // fails due to: could not find implicit value
   //               for evidence parameter of type 
   //               org.scalacheck.Arbitrary[A]
}

Solution

  • The random generator depends on an implicit value of type ClassTag to do its thing. However, A is not known until another trait or class actually extends Foo, so the compiler cannot provide the implicit parameter like it did with fooBound. Try keeping 'a' abstract and then overriding it in other classes, or passing A in as a ClassTag maybe? Look at the source code here to see https://github.com/DanielaSfregola/random-data-generator/blob/master/js/src/main/scala/com/danielasfregola/randomdatagenerator/RandomDataGenerator.scala