Reputation: 2222
I'm new to Scala. I want to read lines from a text file and split and make changes to each lines and output them.
Here is what I got:
val pre:String = " <value enum=\""
val mid:String = "\" description=\""
val sur:String = "\"/>"
for(line<-Source.fromFile("files/ChargeNames").getLines){
var array = line.split("\"")
println(pre+array(1)+mid+array(3)+sur);
}
It works but in a Object-Oriented programming way rather than a Functional programming way.
I want to get familiar with Scala so anyone who could change my codes in Functional programming way?
Thx.
Upvotes: 3
Views: 10914
Reputation: 1722
One traversal and no additional memory
Source
.fromFile("files/ChargeNames")
.getLines
.map { line =>
//do stuff with line like
line.replace('a', 'b')
}
.foreach(println)
Or code which is a little bit faster, according to @ziggystar
Source
.fromFile("files/ChargeNames")
.getLines
.foreach { line =>
//do stuff with line like
println(line.replace('a', 'b'))
}
Upvotes: 9
Reputation: 877
val ans = for (line <- Source.fromFile.getLines) yield (line.replace('a', 'b')
ans foreach println
Upvotes: 5