Posts

Showing posts with the label Scala

How to define Auxiliary Constructor in case class in Scala

We have seen case class previously. We had discussed what is case class, how to create object of case class, list of boilerplate code generated for case class. If you don't know case class, I recommend to understand case class first. Let us revise case class declaration. case class Person(id:Int, name: String) Person class is declared with primary constructor where id and name are parameter. So good so far. The constructor which is not primary constructor, other than primary constructors and overloaded to primary constructor are called auxiliary constructor. How will you declare Auxiliary(other overloaded) constructors. What is syntax of creating auxiliary constructor. Please note that constructors in case class are not really constructor. Actually these are apply methods on companion object. Auxiliary constructor in case class are different than regular class. We can add auxiliary constructors in case class by adding apply() methods in companion object of case class...

case class in Scala

Case class is special type of class. You can class by prepending case keyword  in class declaration. case class Person(id:Int, name: String) Object Creation: You do not need to use new  keyword to create object of case class.  object TestMe { def main(args: Array[String]): Unit = { val person = Person(1,"Prithvi") } } When you create case class, compiler generates apply method for constructor. When you create object, it internally calls apply method. Visibility of variables: If we don't specify visibility(var or val) in variable declaration, It will use val as by default. Since variable are declared as val, accessors will be generated for those variables but not mutators.   Case classes are meant for immutability. Once object of case class is created, it should not be mutated. But we can make case class mutable by declaring variables as var but it will violate the intention of case class  Boilerplate codes: As we have seen,...