On Wed, Oct 10, 2012 at 12:23 AM, Marcel Luethi
<marcel...@gmail.com> wrote:
However, I am still confused about how I should handle failures for functions that do not return a result, such as the following:
def writeXToFile : Unit = {
// some code that may fail
}
To be consistent with other methods that do actually return a value, I'd use Either, with a constant for a successful Unit result:
package object validations {
val RightUnit = Right(Unit)
// and perhaps add some helpers in there too to help make life easier:
class TryRight[A](block: => A) {
def catchLeft[B](handler: PartialFunction[Throwable, Either[B, A]]): Either[B, A] = try Right(block) catch handler
}
def tryRight[A](block: => A) = new TryRight(block)
}
then you can write your method like:
if (somecondition) {
... do stuff ...
RightUnit
} else Left("I failed!")
or
def writeXToFile = tryRight {
... do stuff ...
} catchLeft {
case e: SomeException => "Failed to writeXToFile due to SomeException"
}
Which is of course kinda similar to some of what the new Try class in 2.10 does, but since you are using Either it will mean your types will carry more information about your failure type.
--
Derek Williams