簡體   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