换下风格^_^

What’s the difference between case class and case object in Scala?

Scala admin 621℃ 0评论

在编写看spark源码的时候你会发现有些class  class定义的地方会有class object的定义。这时候你就会有疑问了,class object 和 class  class有啥区别呢?

那么首先我们先总结下case class 和普通的class的区别:

  1. pattern matching support (模式匹配)
  2. default implementations of equals and hashCode  (默认实现equals hashcode)
  3. default implementations of serialization (默认实现serialization)
  4. a prettier default implementation of toString (默认实现toString)
  5. the small amount of functionality that they get from automatically inheriting from scala.Product.

首先我们使用case class 很大部门意图是为了做patten match。那么case object 与case  class的区别是?

下面是英文描述:

What’s the difference between case class and case object in Scala?

Functionally, the difference is the same as between a class and an object. The former creates a blueprint for making objects and the latter defines a singleton object in the scope in which it is declared. In both situations, adding the “case” keyword causes some syntactic sugar to be included. Less of that is needed for the objects than the classes.

Starting with Scala 2.10, you should always use case objects instead of case classes with no arguments. The primary use case here is that you have values you want to pattern match on and some of those need arguments and others don’t. The ones that don’t take arguments should be declared as case objects while the ones that do should be case classes. This makes sense given that you really don’t need multiple instances of an immutable type where the instances would all have identical values.

当我们使用不含参数的时候应该使用case object ,目的是为了避免给相同值的不可变类型创建多个实例。

转载请注明:极豆技术博客 » What’s the difference between case class and case object in Scala?

喜欢 (1)
捐助本站极豆博客全站无广告。如果您觉得本博客的内容对您小有帮助,可以对我小额赞助,您的赞助将用于维持博客运营。

极豆博客

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址