Skip to content

Instantly share code, notes, and snippets.

@trumanw
Created May 4, 2015 06:44
Show Gist options
  • Save trumanw/75a82683aae962bad3e5 to your computer and use it in GitHub Desktop.
Save trumanw/75a82683aae962bad3e5 to your computer and use it in GitHub Desktop.
Case Class in Scala --- Matching Object With Patterns
// 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