I have some misunderstanding in what cases I should use case class or regular class following by best practices. I have already read about differences of both classes but cannot imagine myself real-life examples where is reccommended to use case or regular class.
Could anybody show me real examples with explanation why it's reccommended to do so and not otherwise?
Some Benefits of Case Class/Object 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 classes are good for modeling immutable data. In the next step of the tour, we'll see how they are useful in pattern matching.
The Scala interface for Spark SQL supports automatically converting an RDD containing case classes to a DataFrame. 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.
A case class has all of the functionality of a regular class, and more. When the compiler sees the case keyword in front of a class , it generates code for you, with the following benefits: Case class constructor parameters are public val fields by default, so accessor methods are generated for each parameter.
If you are going to write purely functional code with immutable objects, you should better try avoid using regular classes. The main idea of the functional paradigm is the separation of data structures and operations on them. Case Classes are a representation of a data structure with the necessary methods. Functions on the data should be described in different software entities (e.g., traits, objects).
Regular classes, on the contrary, link data and operations to provide the mutability. This approach is closer to the object-oriented paradigm.
As a result, do not use Case Classes if:
However, in these cases, you should really think about the style of your code because it probably is not functional enough.
Case Classes are normal classes with syntactic sugar. So there is no real big difference, you can do everything with a case class you can do with a class and vice versa.
Case classes just save you a lot of boiler plate code to write.
Perfect fit, as the name suggests, is the use of case classes in pattern matching with case
.
case class MyCase(name: String, age: Int) data : List[MyCase] = ... data foreach { case MyCase(_, age) if age > 21 => println("old enough") case MyCase("fred", _ ) => println("Got you") case _ => ... }
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