It cannot be initialized with params and it will only be compared with itself (singleton). So no advantage for its equals and hash code function. Has anyone come across a case where they find it useful?
A case object is like an object , but just like a case class has more features than a regular class, a case object has more features than a regular object. Its features include: It's serializable. It has a default hashCode implementation.
The one of the topmost benefit of Case Class is that Scala Compiler affix a method with the name of the class having identical number of parameters as defined in the class definition, because of that you can create objects of the Case Class even in the absence of the keyword new.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
Delta Lake with Apache Spark using Scala The case class defines the schema of the table. The names of the arguments to the case class are read using reflection and they become the names of the columns. Case classes can also be nested or contain complex types such as Sequences or Arrays.
You can use case objects as an alternative for enumerations.
Details can be found here: Case objects vs Enumerations in Scala
A simplified example from that question:
sealed trait Currency {
def name: String
def symbol: String
}
case object EUR extends Currency {
val name = "EUR"
val symbol = "€"
}
case object USD extends Currency {
val name = "USD"
val symbol = "$"
}
Enumeration
)sealed
type hierarchy), if a match is not exhaustive.So this code
val ccy: Currency = EUR
ccy match {
case EUR =>
println("Euro")
}
will result in
Warning:(27, 7) match may not be exhaustive.
It would fail on the following inputs: USD
ccy match {
Enumeration
provides withName()
)I think the most important difference is that case objects can be serialized while simple objects cannot.
This makes them very useful as messages with Akka-Remote.
EDIT:
As Rüdiger Klaehn pointed out, this is not the only benefit we get from the case
keyword. There is also:
For classes additionally:
apply
and unapply
implementations(This list may not be exhaustive!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With