简体   繁体   中英

Generating a Scala list of random size

I am creating a scala json using :

lazy val genDefaultValue: Gen[List[JsonPatch]] = {
listOf(
  genJson("/primary", true),
  genJson("/secondary", true),
  genJson("/fallback", true)
)
}

This creates only a random json with one of the item. I am unable to create a list of random size using above 3 list elements. ListSize can be anything between 1 to 3.

genJson is an internal function which creates a Json when passed a path, Gen[T] for expected type.

One option is as follows:

  1. Reorder the list with Random.shuffle() (if you want the order to differ each time).
  2. Call .take(x) on the (optionally shuffled) list, where x is a random value between 1 and 3.

Assuming you're using ScalaCheck and genJson returns an instance of Gen[JsonPatch] , the following code defines a generator for lists of JsonPatch instances:

lazy val genDefaultvalue =
   Gen.listOf(Gen.oneOf(genJson("/primary", true),
                        genJson("/secondary", true),
                        genJson("/fallback", true)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM