开发者

Reading Lines from Sample Code in 'Programming in Scala'

开发者 https://www.devze.com 2023-01-02 14:33 出处:网络
Working through a sample in Chapter 3 of \"Programming in Scala\", the following code doesn\'t seem working on Scala 2.8:

Working through a sample in Chapter 3 of "Programming in Scala", the following code doesn't seem working on 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.")

Scala complains fromFile is expecting type java.io.File. With a bit of searching it seems that I should be using fromPath instead...

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

However, I now get a puzzling error from that (puzzling to a beginner anyways):

... :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

I took a guess at trying...

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

And that didn't work. What's the Scala 2.8 way of making getLines work?


The signature of getLines is this:


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

So it has a default argument. You need to write getLines() instead, so that this default will be used.

0

精彩评论

暂无评论...
验证码 换一张
取 消