What’s the Scala way for this type of read loop?
My answer:
import java.io._
import scala.io._
import scala.collection.mutable._
object PropsParser{
val state = HashMap.empty[String,String]
// Run both ways, should print the same thing
def main(args:Array[String]){
load
println(state)
state.clear
load2
println(state)
}
// A more Scala-ish way? Could be memory hog
def load2{
val src = Source.fromFile(getFile)
src.getLines.map(_.split("=")).foreach((kv) => state += kv(0) -> kv(1).trim)
}
// Dave's original way
def load{
val in = new BufferedReader(new FileReader(getFile))
var line = in.readLine
while (line != null){
val kv = line.split("=")
state += kv(0) -> kv(1)
line = in.readLine
}
in.close
}
def getFile= new File("Some/path/to/your/props/file")
}
2 comments:
Brilliant! I’m so glad to have such a great community to learn from. Thanks.
http://github.com/dcbriccetti/scala-experiments/commit/69880faef3b24b877cc3ab11c758e10d70a8b3a1
Post a Comment