Created
January 14, 2013 00:22
-
-
Save jessitron/4526987 to your computer and use it in GitHub Desktop.
The transformers now return a Result, with more detail on failure than an Option holds. See blog.jessitron.com for the purpose of this post.
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
// from https://github.com/jessitron/BlogCode/blob/master/optionToCustom.scala | |
object transformers { | |
def openFile(n: String) : Result[java.io.File] = { | |
val f = new java.io.File(n) // catch IOException | |
if (f.exists) | |
Success(f) | |
else | |
Failure("File does not exist: " + n) | |
} | |
def readFirstLine (f : java.io.File) : Result[String] = { | |
val source = io.Source.fromFile(f) | |
try { | |
if (!source.hasNext) | |
Failure("File is empty") | |
else | |
Success(source.getLines.next) | |
} finally { | |
source.close | |
} | |
} | |
def parseLine(line : String) : Result[SecretMessage] = { | |
val ExpectedFormat = "The secret message is '(.*)'".r | |
line match { | |
case ExpectedFormat(secretMessage) => Success(SecretMessage(secretMessage)) | |
case _ => Failure("Invalid format") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment