Skip to content

Instantly share code, notes, and snippets.

@missingfaktor
Created November 1, 2015 00:29
Show Gist options
  • Select an option

  • Save missingfaktor/76eab2813cfae1a0eadb to your computer and use it in GitHub Desktop.

Select an option

Save missingfaktor/76eab2813cfae1a0eadb to your computer and use it in GitHub Desktop.
package sudoku.errors
import scala.language.higherKinds
import scala.reflect.ClassTag
object Modes {
trait Mode {
type Result[_, _]
def run[E : ClassTag, A](a: => A): Result[E, A]
}
object Mode {
implicit val exceptionsMode = new Mode {
type Result[E, A] = A
def run[E : ClassTag, A](a: => A): A = a
}
implicit val optionMode = new Mode {
type Result[E, A] = Option[A]
def run[E : ClassTag, A](a: => A): Option[A] = {
try {
Some(a)
} catch {
case _: E => None
}
}
}
implicit val eitherMode = new Mode {
type Result[E, A] = Either[E, A]
def run[E : ClassTag, A](a: => A): Either[E, A] = {
try {
Right(a)
} catch {
case ex: E => Left(ex)
}
}
}
}
}
object Runner {
import Modes._
def parseInt(s: String)(implicit mode: Mode): mode.Result[NumberFormatException, Int] = {
mode.run {
s.toInt
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment