简体   繁体   English

在scala检查中为运行时类型启用隐式导入。 “找不到参数的隐式值”

[英]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 我正在使用ScalaCheck库和ScalaTest在Scala中测试自己的自制Monoid

when attempting to implement DRY tests, I get the implicit error in the title: 尝试实施DRY测试时,标题中出现隐式错误:

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: 这是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? 我想在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 . 您仅使用A 调用 assertIdentityBehaviour ,而其参数可用,但是错误在于其定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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