Created
May 4, 2015 06:42
-
-
Save trumanw/22e6d694fe75dbdceb3e to your computer and use it in GitHub Desktop.
Type Case 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 Typecase extends App { | |
val numObj = new Num(1) | |
val varObj = new Var("var") | |
val mulObj = new Mul(numObj, varObj) | |
// Simplification rule: | |
mulObj match { | |
case m: Mul => | |
m.left match { | |
case n: Num => | |
if (1 == n.value) { | |
println("The left value of the mul is : " + n.value) | |
m.left | |
} else { | |
println("The left value of the mul is not 1.") | |
mulObj | |
} | |
case _ => { | |
println("The left value of the mul is not a Num object.") | |
mulObj | |
} | |
} | |
case _ => { | |
println("The mul is not a Mul object.") | |
mulObj | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment