|
Re: Groovy, JRuby, or Scala: Which JVM Language to Learn Next?
|
Posted: Oct 16, 2007 3:50 PM
|
|
The Scala code example is very imperative. If once rewrites it functionally, I think it shows Scala's strengths more clearly:
import scala.io.Source
val MAXLENGTH = 70
def process(filename: String) = {
Source.fromFile(filename).getLines.map(_.trim).
zipWithIndex.filter{case (line, _) => line.length >= MAXLENGTH}.
map{case (line, num) => (filename, num, line)}.toList
}
println(args.flatMap(name => process(name)).mkString("\n"))
First, the process method has no side effects (it doesn't print.) Instead, it returns a meaningful result that can be used by the caller for the caller's purposes.
The code gets the lines of the file and trims each line.
Next, it "zips" the lines together with a line number.
Next, it filters out the lines that do not violate the MAXLENGTH rule leaving only the lines that violate the rule.
Next, it combines the lines with the filename that contains the line.
The main line collects the results for each file and prints them out.
|
|