Scala case类

探索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用于模拟代数数据类型。
如果一个对象上执行的内部状态计算或显示出其他复杂的行为,它应该是一个普通类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值