Skip to content

Instantly share code, notes, and snippets.

@trumanw
Created May 4, 2015 06:41
Show Gist options
  • Save trumanw/cb6130a4be72ceac07f9 to your computer and use it in GitHub Desktop.
Save trumanw/cb6130a4be72ceac07f9 to your computer and use it in GitHub Desktop.
Type Test/Type Cast in Scala --- Matching Object With Patterns
// Cited from the essay "Matching Object With Patterns"
// Class hierarchy:
trait Expr
class Num(val value: Int) extends Expr
class Var(val name: String) extends Expr
class Mul(val left: Expr, val right: Expr) extends Expr
object TypeTestCast extends App {
val numObj = new Num(1)
val varObj = new Var("var")
val mulObj = new Mul(numObj, varObj)
// Simplification rule:
if (mulObj.isInstanceOf[Mul]) {
val mul = mulObj.asInstanceOf[Mul]
val leftOfMul = mul.left
if (leftOfMul.isInstanceOf[Num]) {
val num = leftOfMul.asInstanceOf[Num]
println("The left value of the mul is : " + num.value)
} else {
println("The left value of the mul is not a Num object.")
}
} else {
println("The mul is not a Mul object.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment