Reputation: 33033
How can I write a Gen[A]
using ScalaCheck that never returns the same object twice?
Gen.oneOf(a,b,c)
can select the same object repeatedly, so that doesn't work.
I'm writing a mutable specification in specs2, and the reason I want to do this is because the behaviour of the system under test should be to only allow each object to be "used" once, in a certain sense.
EDIT: By "the same" I mean the same according to ==
, and the objects are actually strings, so I can't just create the same string each time.
Upvotes: 2
Views: 213
Reputation: 1443
I'm not entirely sure of what you're asking, but there is a generator combinator called Gen.wrap
that evaluates its argument each time the generator itself is evaluated. That way, you can force creation of new objects. See the example below (note that you can skip the use of Gen.value
and instead rely on implicit conversion A => Gen[A]
if you want):
scala> import org.scalacheck._
import org.scalacheck._
scala> class A
defined class A
scala> val g1: Gen[A] = Gen.value(new A)
g1: org.scalacheck.Gen[A] = Gen()
scala> g1.sample.get
res0: A = A@45243a0f
scala> g1.sample.get
res1: A = A@45243a0f
scala> val g2: Gen[A] = Gen.wrap(Gen.value(new A))
g2: org.scalacheck.Gen[A] = Gen()
scala> g2.sample.get
res2: A = A@331d4d66
scala> g2.sample.get
res3: A = A@728aed09
Upvotes: 3