代码之家  ›  专栏  ›  技术社区  ›  T. Stone

从“scala编程”中的示例代码读取行

  •  0
  • T. Stone  · 技术社区  · 15 年前

    通过“scala中的编程”第3章中的示例,以下代码似乎不适用于scala 2.8:

    import scala.io.Source
    
    if (args.length > 0) {
        for (line <- Source.fromFile(args(0)).getLines)
            print(line.length + " " + line)
    }
    else
        Console.err.println("Filename required.")
    

    斯卡拉抱怨 fromFile 应为类型 java.io.File . 经过一番搜索,我似乎应该使用 fromPath 相反…

        for (line <- Source.fromPath(args(0)).getLines)
    

    然而,我现在从中得到了一个令人费解的错误(不管怎么说,对于初学者来说都很费解):

    ... :4: error: missing arguments for method getLines in class Source;
    follow this method with `_' if you want to treat it as a partially applied function
    Error occurred in an application involving default arguments.
        for (line <- Source.fromPath(args(0)).getLines)
                                              ^
    one error found
    

    我猜了一下…

        for (line <- Source.fromPath(args(0)).getLines _)
    

    但这行不通。scala 2.8的制作方法是什么? getLines 工作?

    1 回复  |  直到 15 年前
        1
  •  4
  •   Arjan Blokzijl    15 年前

    GetLines的签名是:

    
    def getLines(separator: String = compat.Platform.EOL): Iterator[String] = new LineIterator(separator)
    

    所以它有一个默认参数。你需要写 getLines() 相反,以便使用此默认值。