您的位置:首页 > 其它

Scala case类

2015-12-19 22:40 211 查看
探索Scala(4)– Case Classes

Case Class

Case class是Scala语言模式匹配功能(pattern match )的基础。如果类定义的时候加上case关键字,那么它就变成了Case Class,如:

case calss CC(x:Int, y:Int)


编译CC,会产生2个class,CC.class和CC$.class.这说明,Scala会给case类自动添加一个单例对象.

apply()和unapply()方法

CC$定义了apply()方法,这样我们就不用敲new关键字,而是通过下面这样的方式来创建实例:

val cc=CC(2,16)


CC$还定义了一个和apply()互补的方法:unapply(),它把CC拆成一个Option.

public final class CC$ ...{
...
public CC apply(int x, int y){
return new CC(x,y);
}

public scala.Option<scala.Tuple2<Object,Object>> unapply(CC cc){
if(cc == null){
return scala.None.None$.MODULE$;
}
return new scala.Some(new scala.Tuple2$mcll$sp(cc.x, cc.y))
}
}


Case Class 默认是Immutable

Case类的字段,默认会被编译器加上val关键字,也就是说:

case class CC(val x:Int, val y:Int)


CC.class反编译之后的相应代码:

public class CC implements scala.Product, scala.Serializable{
private final int x;
private final int y;

public CC(int x,int y){
this.x = x;
this.y = y;
scala.Product$class.$init$(this);
}
public int x(){
return x;
}

public int y(){
return y;
}
}


toString(),hashCode(),equals(),copy()

Scala编译器负责给Case类重写toString(),hashCode()和equals()方法.

copy()方法让Case类实例可以完整地,或者有少量变化的复制自己,如:

val cc = CC(1,2)
val cc1 = cc.copy()
val cc2 = cc.copy(y = 8)


实现Product和Serializable接口

What is the difference between Scala’s case class and class?

Case Classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.

Case类可以被看做是完全依赖他们的构造函数参数的普通的并且不可改变的数据保持的对象。

This functional concept allows us to

use a compact initialisation syntax(
Node(1,Leaf(2),None
)

decompose them using pattern matching

have equality comparisons implicity defined

这个功能可以让我们:

使用紧凑的初始化语法

使用模式匹配将它们分解

有隐式定义的相等比较

In combination with inheritance, case classes are used to minic algebraic datatypes.

If an object performs stateful computations on the inside or exhibits other kinds of complex behaviour, it should be an ordinary class.

与继承相结合,case classes用于模拟代数数据类型。

如果一个对象上执行的内部状态计算或显示出其他复杂的行为,它应该是一个普通类。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: