MaatDeamon
MaatDeamon

Reputation: 9771

Sealed case object vs Enumeratum and issue of serialization in scala

I am learning about Enumerations and its supposed benefit, which are not obvious to me at this point. Indeed the first thing I thought of when I saw it used was, why not using Algebraic DataType instead.

Then found this blog: https://pedrorijo.com/blog/scala-enums/

With the following example:

sealed trait Weekday

case object Monday extends Weekday
case object Tuesday extends Weekday
case object Wednesday extends Weekday
case object Thursday extends Weekday
case object Friday extends Weekday
case object Saturday extends Weekday
case object Sunday extends Weekday

But then

Problems with sealed case objects ...

  • there is no simple way to retrieve all the enumeration values
  • there are no default serialize/deserialize methods
  • there is no default ordering between enumeration values - this can be achieved manually by including some info on the values ...

While i understand point 1 and 3 and indeed i barely have this needs, i don't understand point 2

there are no default serialize/deserialize methods

My understanding is that case object are serializable. Hence I do not get it?

Can someone explain?

Also I really don't see the advantage over using algebraic datatype.

Upvotes: 0

Views: 513

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170899

there are no default serialize/deserialize methods

My understanding is that case object are serializable. Hence I do not get it ?

If you read the other examples you can see the author means methods to convert to/from String. Of course, toString gives you one direction:

Monday.toString == "Monday"

But there's no method get the value from its name unless you write your own:

Weekday.???("Monday") == Monday

Upvotes: 3

Tomer Shetah
Tomer Shetah

Reputation: 8539

At the beginning of the article, it is elaborating about the native Scala enumeration. One of the advantages shown there of the native Scala enumeration, is the serialization/deserialization, followed by the example:

scala> Weekday.Monday.toString
res0: String = Monday

scala> Weekday.withName("Monday")
res1: Weekday.Value = Monday

When using case objects, let's assume we have:

sealed trait Weekday

case object Monday extends Weekday

Then you can serialize easily:

scala> Monday.toString
res0: String = Monday

But having the string Monday, it is not easy to get back the case object Monday.

Upvotes: 2

Related Questions