Created
May 4, 2015 06:44
-
-
Save trumanw/75a82683aae962bad3e5 to your computer and use it in GitHub Desktop.
Case Class 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 | |
case class Num(val value: Int) extends Expr | |
case class Var(val name: String) extends Expr | |
case class Mul(val left: Expr, val right: Expr) extends Expr | |
object CaseClass extends App { | |
val numObj = new Num(1) | |
val varObj = new Var("var") | |
val mulObj = new Mul(numObj, varObj) | |
// Simplification rule: | |
mulObj match { | |
case Mul(Num(1), Var(x)) => { | |
println("The right value of the mul is : " + x) | |
Var(x) | |
} | |
case _ => mulObj | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment