Scala - 发现错误类型不匹配:需要 List[String]:scala.collection.IterableOnce[Nothing]

Scala - Error type mismatch found : List[String] required: scala.collection.IterableOnce[Nothing]

我在执行程序时遇到以下错误....有人帮我解决这个问题吗?

value ++= is not a member of List[Nothing]
  Expression does not convert to project because:
    type mismatch;
     found   : List[String]
     required: scala.collection.IterableOnce[Nothing]
    expansion: merge = merge.++(Source.fromFile(filepath).getLines.toList)
       merge ++= Source.fromFile(filepath).getLines.toList

下面是我的代码

var merge = List()

for (i <- 1 to batchSize) {
      val filepath = new File(s"d://Assignment//data//${foldername}//out//file-${filecount}-part-000${i - 1}.txt")
      filepath.getParentFile().mkdir()
      val writer = new FileWriter(filepath)
      breakable {
        while (count < lines.length) {
          writer.write(lines(count))
          writer.write("\n")
          val size = copyFile(filepath, foldername)
          writer.flush()
          count += 1
            if (size == partition) { break } }
          writer.close() }
          merge ++= Source.fromFile(filepath).getLines.toList
    }

您需要指定merge的类型:

var merge = List.empty[String]

但是如果没有 var,这段代码会更好,方法是在几个地方使用 flatMap,例如

val merge = (1 to batchSize).flatMap { i =>
  ...
  Source.fromFile(filepath).getLines.toList
}