标签:
Scala Case Class
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://yjplxq.blog.51cto.com/4081353/1415533
case classes 又是做什么的呢? 你可以就把他理解成一个普通的class,但是又略有不同,总结如下:
不需要写 new, 但是可以写
默认是public ,在任何地方调用
默认实现了toString
不能被继承
官方原文:
It makes only sense to define case classes if pattern matching is used to decompose data structures.
当然,只有在pattern matching下有意义这话未免有所偏激,至少部分老程序员会有其他意见:
get auto-generated equals, hashCode, toString, static apply() for shorter initialization, etc.
如下官网示例,
/** * @author: Lenovo(2015-04-13 13:37) */ // 抽象父类 abstract class Term // case class case class Var(name: String) extends Term // case class case class Fun(arg: String, body: Term) extends Term // case class case class App0(f: Term, v: Term) extends Term object TermTest extends App { def printTerm(term: Term) { term match { case Var(n) => print(n) case Fun(x, b) => print("^" + x + ".") printTerm(b) case App0(f, v) => print("(") printTerm(f) print(" ") printTerm(v) print(")") } } def isIdentityFun(term: Term): Boolean = term match { case Fun(x, Var(y)) if x == y => true case _ => false } val id = Fun("x", Var("x")) val t = Fun("x", Fun("y", App0(Var("x"), Var("y")))) printTerm(t) println println(isIdentityFun(id)) println(isIdentityFun(t)) }
运行,
^x.^y.(x y) true false
标签:
原文地址:http://my.oschina.net/xinxingegeya/blog/399977