Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active December 17, 2015 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frgomes/9bcdad68a2f50c4c6a2c to your computer and use it in GitHub Desktop.
Save frgomes/9bcdad68a2f50c4c6a2c to your computer and use it in GitHub Desktop.
Scala - Partial functions with orElse
import java.io._
val osURL: PartialFunction[Option[String], OutputStream] = {
case Some(name) => new java.io.FileOutputStream(new java.io.File(name))
if(name.contains(":"))
}
val osLocalFile: PartialFunction[Option[String], OutputStream] = {
case Some(name) => new java.io.FileOutputStream(new java.io.File(name))
}
val osStdout: PartialFunction[Option[String], OutputStream] = {
case _ => System.out
}
val makeOutputStream = osURL orElse osLocalFile orElse osStdout
val args1 = Seq.empty[String]
val os1 = makeOutputStream(args1.headOption)
val pw1 = new PrintWriter(os1)
pw1.write("In this case, this text is printed out to the console.\n")
val args2 = Seq("output.txt")
val os2 = makeOutputStream(args2.headOption)
val pw2 = new PrintWriter(os2)
pw2.write("In this case, this text is printed out to a file.\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment