Created
August 3, 2017 10:04
-
-
Save fmasion/f1fa279592f2dd5213e7fb9e743a54ba to your computer and use it in GitHub Desktop.
Loan sacla basics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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