簡體   English   中英

for循環,Scala中的類型不匹配

[英]Type mismatch in for loop, Scala

我遇到了persistand錯誤。

var pageArray = new Array[ImageIcon](tempDir.size)
for (page <- tempDir.toList) {
    pageArray += new ImageIcon(page.getAbsolutePath)
}
Some(new Pages(pageArray)) //returns class with constructor Array[ImageIcon]

當我嘗試編譯時,此代碼塊會產生類型不匹配錯誤:

Error:(43, 18) type mismatch;
 found   : javax.swing.ImageIcon
 required: String
                pageArray += new ImageIcon(page.getAbsolutePath)
                             ^

我不明白從哪里獲取String的,以及當我嘗試以下代碼時:

var pageArray = new Array[ImageIcon](tempDir.size)
for (page <- tempDir.toList) {
    pageArray += "test" //new ImageIcon(page.getAbsolutePath)
}
Some(new Pages(pageArray)) //returns class with constructor Array[ImageIcon]

我得到以下內容:

Error:(43, 15) type mismatch;
 found   : String
 required: Array[javax.swing.ImageIcon]
                pageArray += "test"//new ImageIcon(page.getAbsolutePath)
                          ^

首先, +=不是合適的運算符-將值附加到可以使用:+的數組中:

scala> var intArray = new Array[Int](4)
intArray: Array[Int] = Array(0, 0, 0, 0)

scala> intArray :+ 5
res2: Array[Int] = Array(0, 0, 0, 0, 5)

第二,如您在上面的示例中看到的,創建大小為tempDir.size的數組然后追加到數組中沒有多大意義-您最終得到的大小為2 * tempDir.size的數組。

我認為您要嘗試做的一個更好的實現是:

tempDir.map(page => new ImageIcon(page.getAbsolutePath)).toArray

這將簡單地創建一個新的Array,並使用提供的匿名函數映射每個原始集合的值。 使用Scala集合時,通常建議查找此類高階函數,而不是遍歷集合並更新可變集合。

現在,關於此String的來源:由於scala.Array沒有+=運算符,因此編譯器會尋找將其隱式轉換為可轉換的內容。 它發現:

implicit final class any2stringadd[A](self : A) extends scala.AnyVal  {
  def +(other : scala.Predef.String) : scala.Predef.String = { /* compiled code */ }
}

它將調用self.toString ,然后將值附加在右側,並期望它是一個String。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM