Last active
December 17, 2015 11:16
-
-
Save frgomes/9bcdad68a2f50c4c6a2c to your computer and use it in GitHub Desktop.
Scala - Partial functions with orElse
This file contains 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
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