lundi 20 avril 2015

Implicit Collision with ScalaCheck

I wrote a ScalaCheck property:


scala> import org.scalacheck.{Properties, Arbitrary, Gen}
import org.scalacheck.{Properties, Arbitrary, Gen}

scala> import org.scalacheck.Prop.forAll
import org.scalacheck.Prop.forAll

scala> import org.scalacheck.Prop._
import org.scalacheck.Prop._

scala> import org.scalacheck.Arbitrary._
import org.scalacheck.Arbitrary._

Making a Gen and Arbitrary for Foo

scala> case class Foo(x: Any)
defined class Foo

scala> val fooGen: Gen[Foo] = arbitrary[Int].map(Foo(_))
fooGen: org.scalacheck.Gen[Foo] = org.scalacheck.Gen$$anon$6@74da2066

scala> implicit val arbitraryFoo: Arbitrary[Foo] = Arbitrary(fooGen)
arbitraryFoo: org.scalacheck.Arbitrary[Foo] = org.scalacheck.Arbitrary$$anon$3@6f4c397e

scala> forAll { _: Foo => (true == true) }
res2: org.scalacheck.Prop = Prop

However, I'd like to specify that this property holds for a Double too.

So I added another Gen[Foo] and Arbitrary[Foo]:

scala> val fooGenDouble: Gen[Foo] = arbitrary[Double].map(Foo(_))
fooGenDouble: org.scalacheck.Gen[Foo] = org.scalacheck.Gen$$anon$6@31d5eb6c

scala> implicit val arbitraryFooDouble: Arbitrary[Foo] = Arbitrary(fooGenDouble)
arbitraryFooDouble: org.scalacheck.Arbitrary[Foo] = org.scalacheck.Arbitrary$$anon$3@6a43082d

But, when I try to define another property, I get an ambiguous implicit:

scala> forAll { _: Foo => (true == true) }
<console>:22: error: ambiguous implicit values:
 both value arbitraryFoo of type => org.scalacheck.Arbitrary[Foo]
 and value arbitraryFooDouble of type => org.scalacheck.Arbitrary[Foo]
 match expected type org.scalacheck.Arbitrary[Foo]
              forAll { _: Foo => (true == true) }

How is this typically handled in a Scalacheck test?

Aucun commentaire:

Enregistrer un commentaire