Differences between case object T and case class T() when defining ADT?

穿精又带淫゛_ 提交于 2021-02-10 12:22:08

问题


Let's say in scala I have an ADT as follows:

sealed trait Animal

object Animal {
case class Lion(name: String)    extends Animal
case class Elephant(name:String) extends Animal
case object Tiger                extends Animal
}

Here, is it preferable to declare Tiger as a case object or should it be declared as an empty case class i.e case class Tiger() ? Does one have any advantage over other?


回答1:


If there is the only Tiger it should be an object. If there can be several equal Tigers it should be a class.

val tiger = Tiger()
val tiger1 = Tiger()
tiger == tiger1 // true
tiger eq tiger1 // false



回答2:


My two cents: I think if you would like to declare empty case class like Tiger in your case - stop and think, because it highly likely you are doing something wrong.

Case classes were designed for easy work with structured data - but if there is no data declared in case class, it is unclear how it should be interpreted from the business logic point of view. On the other hand - case object clearly describes certain type of signal, which does not need any additional data, because it singleton.

I'd propose a bit practical example:

/**
* Sum type describing abstract operation over some user profile in theoretical social network
*/
sealed trait UserProfileOperation

/**
* User requests edit certain field with value in it's profile
*/
case class Edit(field: String, value: String) extends UserProfileOperation 

/**
* User requests to delete own profile - no additional data required, 
* so it is always singleton type signal
*/
case object Delete extends UserProfileOperation 

Hope this helps!



来源:https://stackoverflow.com/questions/60137014/differences-between-case-object-t-and-case-class-t-when-defining-adt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!