Skip to content

Instantly share code, notes, and snippets.

@BenWhitehead
Created January 20, 2015 19:54
Show Gist options
  • Save BenWhitehead/70953700795d4bb2967d to your computer and use it in GitHub Desktop.
Save BenWhitehead/70953700795d4bb2967d to your computer and use it in GitHub Desktop.
Scala Type check Try Success parameter
import org.scalatest.FreeSpec
import scala.reflect.ClassTag
import scala.util.{Failure, Success, Try}
class Data(a: => AnyRef) {
def get() = a
}
class TypeCheckingBranches extends FreeSpec {
"Type checking should" - {
"Success(a: A)" in {
assert(1 === execute[String](new Data("a")))
}
"Success(_)" in {
assert(2 === execute[String](new Data(List(1))))
}
"Failure(t)" in {
assert(3 === execute[String](new Data(throw new RuntimeException)))
}
}
def execute[A](input: Data)(implicit ct: ClassTag[A]): Int = {
Try(input.get()) match {
case Success(x: A) if ct.runtimeClass.isInstance(x)=> 1
case Success(_) => 2
case Failure(e) => 3
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment