0

By definition:

Scala supports the notion of case classes. Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.

What is the meaning of regular classes which export their constructor parameters?

In general I understand how you can use them.So you can have something in the lines of this:

abstract Class Vehicle
case class Car extends Vehicle
case class Plane extends Vehicle
case class SpaceShip extends Vehicle

And then apply a pattern match on each Vehicle to see what exactly it is however isn't this possible with all classes?

x match {
case List(x): something
case Stream(x): something else
}

So what is the main difference when writing case class instead of just class ?

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
Bula
  • 2,398
  • 5
  • 28
  • 54
  • 1
    "export their constructor parameters" is, I think, just a fancy way of saying "act as though all their constructor parameters were declared `val`". You can pattern match `List` and `Stream` because their *companion objects* define `unapply` or `unapplySeq` methods. You can do this "by hand" to make a "normal" class that can be pattern matched, but for a case class a companion object with these methods will be autogenerated. If your class doesn't have a companion object with `unapply` or `unapplySeq` you can't pattern match; `class A(s: String); x match { case A(y) }` won't compile. – lmm Nov 12 '14 at 17:01
  • @lmm Oh I wasn't aware of that. So if you have a plain class in scala with nothing written in it you cannot use pattern matching for it? – Bula Nov 12 '14 at 17:15
  • You can still pattern match like `case a: A => a.s`, but you can't do a "destructuring" pattern match `case A(y) => y`. – lmm Nov 12 '14 at 18:40

1 Answers1

1

Case class is different from normal class in following ways-

1) You can create instance of case class without new keyword

2) You can do pattern matching with case class

3) The constructor parameters of case classes are treated as public values and can be accessed directly like -

abstract class Term

case class Var(name: String) extends Term

val x = Var("x") println(x.name)

Please refer http://docs.scala-lang.org/tutorials/tour/case-classes.html and http://www.scala-lang.org/old/node/258

For more details about case classes

swaraj patil
  • 209
  • 2
  • 5