5

我看到了这个线程:

Scala 2.8 和 Scala 2.7 之间最大的区别是什么?

它似乎涵盖了一些更改,但似乎没有提到我遇到的第一个编译问题。有什么建议么?

  • 类型参数的种类(Iterable[Any] with (A with Int) => Any)不符合类 GenericCompanion 中类型参数(CC 类型)的预期种类。Iterable[Any] with (A with Int) => Any 的类型参数与类型 CC 的预期参数不匹配:没有类型参数,但类型 CC 有一个
  • 无法创建对象,因为未定义类型 => Iterator[java.io.File] 的特征 IterableLike 中的方法迭代器
  • 无法创建对象,因为未定义类型 => Iterator[V] 的特征 IterableLike 中的方法迭代器
  • 覆盖类型 => Iterator[java.io.File] 的 trait IterableLike 中的方法元素;方法元素需要“覆盖”修饰符
  • 覆盖类型 => Iterator[V] 的 trait IterableLike 中的方法元素;方法元素需要“覆盖”修饰符

这是有问题的代码:

/**
 * Filesystem walker.
 * <p>
 * Less magic version of: http://rosettacode.org/wiki/Walk_Directory_Tree#Scala
 */
object FsWalker {
  /**
   * Recursive iterator over all files (and directories) in given directory.
   */
  def walk(f: File): Iterable[File] = new Iterable[File] {
    def elements = {
      if (f.isDirectory()) {
        // recurse on our child files
        f.listFiles.elements.flatMap(child => FsWalker.walk(child).elements)
      } else {
        // just return given file wrapped in Iterator
        Seq(f).elements
      }
    }
  }
}
4

2 回答 2

7

前者elements是现在iterator

您应该使用 -Xmigration 进行编译,以获得有关如何将代码从 2.7 移植到 2.8 的有用提示。

于 2010-08-09T23:46:13.633 回答
5

这里的关键是确保将方法迭代器与 Iterable 一起使用。Scala 2.8.0 也做了很多工作来确保类型在集合调用中保持一致。

scala> val x = new Iterable[String] {
     | def iterator = List("HAI", "YOU", "GUYS").iterator
     | }
x: java.lang.Object with Iterable[String] = line18(HAI, YOU, GUYS)

我也会考虑使用 Stream 而不是迭代器。迭代器方法在调用迭代器方法时会构造整个文件集。流可能是惰性的。

scala> def files(f : File) : Stream[File] = {
     |   if(f.isDirectory) {                   
     |     f.listFiles.toStream.map(files).flatten
     |   } else Stream(f)
     | }
files: (f: java.io.File)Stream[java.io.File]

scala> files(new File("/home/jsuereth/projects/scala/scala"))
res1: Stream[java.io.File] = Stream(/home/jsuereth/projects/scala/scala/build/manmaker/classes/scala/man1/sbaz.class, ?)

scala> res1 take 10 foreach println
/home/jsuereth/projects/scala/scala/build/manmaker/classes/scala/man1/sbaz.class
/home/jsuereth/projects/scala/scala/build/manmaker/classes/scala/man1/scala$$anon$1.class
...

或者,如果您想在流中包含目录,请尝试以下操作:

scala> def files_with_dirs(f : File) : Stream[File] = {
     | if(f.isDirectory) Stream.cons(f, f.listFiles.toStream.map(files).flatten)
     | else Stream(f)
     | }
files_with_dirs: (f: java.io.File)Stream[java.io.File]
于 2010-08-10T02:03:42.770 回答