Scala read file

621 ワード

// use loan pattern
// close resource after used
def using[A <: def="" close="" unit="" b="" a=""> B): B = {
  try {
    f(resource)
  } finally {
    resource.close()
  }
}

// use Option as return
def readTextFile(filename: String): Option[List[String]] = {
  try {
    val lines = using(Source.fromFile(filename)) {
      source =>
        source.getLines.toList
    }
    Some(lines)
  } catch {
    case e: Exception => None
  }
}

// print lines
val lines = readTextFile(filename).get
lines.foreach { line =>
  println(line)
}