简体   繁体   中英

enable implicit import for runtime type in scala check. “could not find implicit value for parameter”

I'm testing my own home-brewed Monoid classes in scala using the ScalaCheck library and ScalaTest

when attempting to implement DRY tests, I get the implicit error in the title:

Error:(16, 12) could not find implicit value for parameter arbA: org.scalacheck.Arbitrary[A]
    forAll { (a: A) =>
       ^

here is the implementation of intAddition Monoid:

trait Monoid[A] {
  def op(a1: A, a2: A): A
  def zero: A
}

object Monoid {
...
  val intAddition: Monoid[Int] = new Monoid[Int] {
    override def op(a1: Int, a2: Int): Int = a1 + a2
    override def zero: Int = 0
  }
...
}

And the test suite:

import org.fpinscala.monoids.Monoid._
import org.fpinscala.testutils.UnitSpec
import org.scalatest.prop.PropertyChecks
import org.scalacheck.Arbitrary._

import scala.language.implicitConversions

class MonoidSpec extends UnitSpec with PropertyChecks {

  def assertIdentityBehaviour[A](M: Monoid[A]): Unit = {
    import M._
    forAll { (a: A) =>
      op(zero, a) should be(a)
      op(a, zero) should be(a)
    }
  }

  behavior of "intAdditionMonoid"

  it should "obey identity laws" in {
    assertIdentityBehaviour(intAddition)
  }
}

This code compiles but fails at runtime (runtime type erasure?). Is what I'm trying to achieve possible in Scala?

This code compiles

It doesn't; the error you give is a compilation error. It should be fixed by adding the implicit parameter it complains about:

def assertIdentityBehaviour[A](M: Monoid[A])(implicit arbA: Arbitrary[A]) = ...
// or equivalently, def assertIdentityBehaviour[A: Arbitrary](M: Monoid[A]) = ...

You are calling assertIdentityBehaviour only with A for which the parameter is available, but the error is in its definition .

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