What is the case class?why we need to go with it?what is the difference btwn normal class and case class?


What is the case class?why we need to go with it?what is the difference btwn normal class and case class??


Let us take an example with having two classes with parameters and those becomes fields if we give them val keyword. so they are now readable from outside which are immutable aswell.

class Category(
  val name: String,
  val parent: Option[Category])

class Product(
  val name: String,
  val description: String,
  val category: Category)

and now let us see better option case classes

case class Category(
   name: String,
   parent: Option[Category])

case class Product(
  name: String,
  description: String,
  category: Category)

Here we don’t need to mention Val keyword they are automatically promoted to fields and also we need don’t to instantiate the new keyword to create an object because case classes have an apply method by default which takes care of object construction.


Thank you so much Sunil.
Is this alone a advantage or anything else


yes there are other important advantages as well like pattern matching, companion objects etc.

Here is the video about case classes in detail https://www.youtube.com/watch?v=oZwjtHJh4sc


can we define a above case class like this
case class Category
name: String,
parent: Option[Category]

case class Product
name: String,
description: String,
category: Category


A case class requires the keywords case class, an identifier, and a parameter list.

For example like this

case class Book(name: String)


If I want to define any method inside case class,will it possible like below?

case class Book(name: String)
def method1:unit={ }


Thanks you so much Sunil.Kindly provide me your mail Id and mobile number.It would be great helpful for me


yes we can define methods inside a case class like this below

case class Student(name: String) {
  def isQualified = "Student(" + name + ")"

val s = Student(“xyz”)


@Vigneshrajan I deleted your details. Please don’t share any personal information like email and mobile numbers on forums.