Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.
abstract class Term
case class Var(name: String) extends Term
case class Fun(arg: String, body: Term) extends Term
case class App(f: Term, v: Term) extends Term
1. To facilitate the construction of case class instances, Scala does not require that the
new
primitive is used. One can simply use the class name as a function.The constructor parameters of case classes are treated as public values and can be accessed directly.
val x = Var("x")
Console.println(x.name)
2. For every case class the Scala compiler generates
equals
method which implements structural equality and a toString
method.
3. It makes only sense to define case classes if pattern matching is used to decompose data structures.
object TermTest extends Application {
def printTerm(term: Term) {
term match {
case Var(n) =>
print(n)
case Fun(x, b) =>
print("^" + x + ".")
printTerm(b)
case App(f, v) =>
Console.print("(")
printTerm(f)
print(" ")
printTerm(v)
print(")")
}
}}
Reference:
http://www.scala-lang.org/old/node/107.html
No comments:
Post a Comment