Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

case classes
scala

What are Case Classes in Scala?

Dian Us Suqlain

Case Classes in Scala are similar to regular classes, but there are a few new keywords that have to be written.

Case Classes are good for modeling immutablean object whose state cannot be modified after it is created. data.

All parameters listed in a Case Class are public and immutable by default. In a Normal Class, parameters are private by default.

Case Class vs Normal Class

Case Classes are just like Regular Classes in Scala, except for a few distinct differences:

  • Case Classes can be pattern matched
  • Case Classes automatically define hashcode and equals
  • Case Classes automatically define getter methods for the constructor arguments

You have to specify the var variable in the constructor argument if you want to automatically define getter and setter methods.

Syntax

case class ClassName(parameters) {
    var obj1 = ClassName()
}

You can observe that the new keyword is not used to create an object inside a Case Class.

Code

Following is the example of adding two variables inside a Case Class:

case class CaseClass (a:Int, b:Int)  
  
object MainObject {  
    def main(args:Array[String]) : Unit = {  
        var c =  CaseClass(10,10)  
        println("Sum of a & b = " + c.a + c.b)  
        //println("b = " + c.b)  
    }  
}  
Scala Case Class Example adding two numbers

RELATED TAGS

case classes
scala

CONTRIBUTOR

Dian Us Suqlain
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring