Skip to content

Instantly share code, notes, and snippets.

@fmasion
Created August 3, 2017 10:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmasion/f1fa279592f2dd5213e7fb9e743a54ba to your computer and use it in GitHub Desktop.
Save fmasion/f1fa279592f2dd5213e7fb9e743a54ba to your computer and use it in GitHub Desktop.
Loan sacla basics
A utiliser avec les ressouces "Closable" (fichers, connections bdd etc...)
exemple :
def withFile[A](name: String, encoding: String = "UTF-8")(func: Iterator[String] => A): A = {
val source = Source.fromFile(name, encoding)
val lines = source.getLines()
try {
func(lines)
} finally {
source.close()
}
}
usage:
withFile("greetings.txt") { lines =>
lines.length
}
On peut aussi descendre d'un niveau si on veux avoir acces à chaque ligne plutôt qu'a l'ensemble des lignes
Du coup on lui ajoute la responsabilité d'itérer
def withFileLine[A](name: String, encoding: String = "UTF-8")(func: String => A): Iterator[A] = {
val source = Source.fromFile(name, encoding)
val lines = source.getLines()
try {
lines.map(func)
} finally {
source.close()
}
}
usage:
val ParsedLines: Iterator[ParsedLine] = withFileLine("greetings.txt") { ligne =>
parse(ligne) // parse : String -> ParsedLine
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment