Created
May 4, 2015 06:41
-
-
Save trumanw/cb6130a4be72ceac07f9 to your computer and use it in GitHub Desktop.
Type Test/Type Cast in Scala --- Matching Object With Patterns
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
// 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