繁体   English   中英

使用Scala的生成器习惯用法时,运行时“找不到参数的隐式值”错误

[英]Runtime “could not find implicit value for parameter” error when using Scala's builder idiom

我正在编写一个Scala类,该类实现任意对象的二维矩阵。 我需要的IndexedSeq嵌套的IndexedSeq对象对更专业,但是扩展collections类太过分了,所以我要编写自己的类。 为了从矩阵类中的方法返回正确的类型,我使用了隐式生成器习惯用法,但是在运行时,我收到了“无法为参数找到隐式值”错误,我不理解。

我的矩阵类的精简版本如下所示。

trait MatrixBuilder[V, M <: Matrix[V]] {
  def apply(values: IndexedSeq[IndexedSeq[V]]): M
}

abstract class Matrix[V](values: IndexedSeq[IndexedSeq[V]]) extends Function2[Int, Int, V] {

  def apply(row: Int, col: Int): V = values(row)(col)

  def set[M <: Matrix[V]](row: Int, col: Int, value: V)(implicit builder: MatrixBuilder[V, M]): M =
    builder(values.updated(row, values(row).updated(col, value)))
}

case class IntMatrix(values: IndexedSeq[IndexedSeq[Int]]) extends Matrix[Int](values)

object IntMatrix {
  def apply(n: Int) = new IntMatrix(IndexedSeq.fill(n, n)(0))

  implicit object IntMatrixBuilder extends MatrixBuilder[Int, IntMatrix] {
    def apply(values: IndexedSeq[IndexedSeq[Int]]) = IntMatrix(values)
  }
}

我希望set函数设置指定的单元格,然后返回正确类型的新矩阵。 因此,我希望IntMatrix(2).set(0,0,5)返回一个除(0,0)以外的所有单元中都为零的IntMatrix对象,该对象应具有5。相反,在运行时出现以下错误。

error: could not find implicit value for parameter builder: MatrixBuilder[Int,M]
    IntMatrix(2).set(0,0,5)

我在这里做错了什么?


如下pedrofurla所述,如果您首先运行import IntMatrix._行,则该代码在REPL中import IntMatrix._ 并查看集合文档 ,使用构建器的源代码中似乎有类似的import语句。 我尝试将一个添加到我的IntMatrix类。

case class IntMatrix(values: IndexedSeq[IndexedSeq[Int]]) extends Matrix[Int](values) {
    import IntMatrix._
}

但这没有效果。 (实际上,我的IDE IntelliJ将其标记为未使用的import语句。)

为了比较,我复制了逐字链接的馆藏文档中的RNA序列示例。 import RNA._import RNA._行未标记为多余,并且所有操作均返回正确的类型。 如果答案是我需要添加一个import IntMatrix._ ,我不知道该放在哪里。

这个小代码在这里工作:

scala> import IntMatrix._
import IntMatrix._

scala> IntMatrix(2).set(0,0,5)
res1: Mat.IntMatrix = <function2>

隐式参数由编译器在调用站点中填充,因此它们必须在被调用的作用域set可用。

暂无
暂无

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

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