Search code examples
scalascalacheck

Create generator from list of generators


I want to create Generator from multiple generators. I have list of generators

val generators: List[Gen] = List(Gen[Int], Gen[Double], Gen[String], ...)

I don't know what is the size of the list, it could be any size

I want to create something like this:

val listGen: Gen[List[Any]] = createListGenerator(generators)

Solution

  • If you want listGen to give you an arbitrary number of elements in an arbitrary order that are drawn from one or more of the generators in generators, you can do the following:

    // Scala's type inference gets a bit finicky when combining Anys with CanBuildFroms
    val comboGen = Gen.sequence[List[Any], Any](generators).flatMap(Gen.oneOf[Any])
    val listGen = Gen.listOf(comboGen)
    

    Alternatively, if you want to have exactly the same number of elements get generated by listGen as there are elements in generators and in the same order, you can simply do

    val listGen = Gen.sequence[List[Any], Any](generators)