Showing posts with label scala. programming. Show all posts
Showing posts with label scala. programming. Show all posts

Thursday, February 19, 2009

What’s the Scala way for this type of read loop?


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")

}