Created
January 20, 2015 19:54
-
-
Save BenWhitehead/70953700795d4bb2967d to your computer and use it in GitHub Desktop.
Scala Type check Try Success parameter
This file contains hidden or 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 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