SlideShare a Scribd company logo
Scala – Case of Case Classes




                 By VulcanMinds
Case Classes - Concepts
Scala provides ‘Case Classes’ to do elegant comparisons in your code about the class
object types. for e.g. a case class looks like…


scala> abstract case class Animal
defined class Animal

scala> case class Dog(breed:String,name:String) extends Animal;
defined class Dog

scala> case class Cat(breed:String,name:String) extends Animal;
defined class Cat

Now Create instances……
scala> var anAnimal:Animal = new Cat(“Indonesian","Silly");
anAnimal: Animal = Animal()

scala> var anAnimal2:Animal = new Dog("Alsatian","Biscuit");
anAnimal2: Animal = Animal()

scala> anAnimal match {
   | case Cat(breed,name) => println("The animal was cat with name :" + name + “ and breed:" + breed)
   | case Dog(breed,name) => println("The animal was dog with name :" + name + “ and breed:" + breed)}
The animal was cat with name :Silly and breed:Indonesian
Case Classes - Concepts
More examples.....

scala> def anyGobbler(anyAnimal:Any) {
   | anyAnimal match {
   | case Dog(breed , name) => println("You gave me a Dog with value :" + anyAnimal);
   | case Cat(breed, name) => println("You gave me a Cat :" + anyAnimal);
   | case _ => println("Excuse me, why did you send me something " + anyAnimal);
   | }}
anyGobbler: (anyAnimal: Any)Unit

scala> var myDog:Dog = new Dog(“Alsatian",“biscuit")
myDog: Dog = Animal()


scala> var myCat:Cat = new Cat("indonesian","silly")
myCat: Cat = Animal()

scala> anyGobbler(myDog);
You gave me a Dog with value :Animal()

scala> anyGobbler(myCat);
You gave me a Cat :Animal()

scala> anyGobbler("garbage");
Excuse me, why did you send me something garbage
Case Classes - Concepts
Accessing the members of the case classes instances….


scala> def anyGobbler2(anyAnimal:Any) {
   | anyAnimal match {
   | case Dog(breed,name) => println("You gave me a Dog with breed ::" + breed + " with name:" + name);
   | case Cat(breed, name) => println("You gave me a Cat with breed:" + breed + " with name:" + name);
   | case _ => println("Excuse me, why did you give me something else" + anyAnimal);
   |}
   |}
anyGobbler2: (anyAnimal: Any)Unit
scala> anyGobbler2(new Dog("Alsatian","Biscuit"));
You gave me a Dog with breed ::Alsatian with name: Biscuit

scala> anyGobbler2(new Cat("Indonesian","Silly"));
You gave me a Cat with breed:Indonesian with name :Silly
Define a new animal anyGobble2 doesn’t know…..
scala> class Mouse(type:String) extends Animal;
defined class Mouse

scala> anyGobbler2(new Mouse("JerryType"));
Excuse me, why did you give me something else Animal()
The apply() method
You can define an apply(….) method for any Class or an Object and it will be called anytime you append a pair of parenthesis ‘( )’
to the object of that class. Like below



scala> object Test {
    | def apply(x:Int) = {
    | x*5 }
    |}
defined module Test
Calling it is as below …
scala> var a = Test(100)
a: Int = 500}

scala> class CTest {
   | def apply(x:Int) = {
   | x*5}
   |}
defined class CTest


scala> var s = new CTest
s: CTest = CTest@5bbe2de2

scala> var p = s(100);
p: Int = 500
The unapply() method
Similarly you also define an unapply(….) method for any Class or an Object and it will be called during a case match block of
code as below…

scala> object Test {
   | def unapply(x:Int):Option[Int] = {
   | if (x > 5) Some(x) else None}
   |}
defined module Test

scala> for(i <- 1 to 10) i match {
   | case Test(a) => println(" value of a " + a)
   | case _ => println("not matching")}
not matching
not matching
not matching
not matching
not matching
 value of a 6
 value of a 7
 value of a 8
 value of a 9
 value of a 10
class Vs case class
scala> class Person(name:String)                                   scala> case class CPerson(name:String)
defined class Person                                               defined class CPerson

scala> val p = new Person("Tom")                                   scala> var cp = CPerson("Jerry")
p: Person = Person@362a7b                                          cp: CPerson = CPerson(Jerry)

scala> val p2 = new Person("Tom")                                  scala> val n = cp.name
p2: Person = Person@2cd0a9b2                                       n: String = Jerry

scala> if(p == p2) true else false                                 scala> var cp2 = CPerson("Jerry")
res12: Boolean = false                                             cp2: CPerson = CPerson(Jerry)

scala> val m = p.name                                              scala> if(cp == cp2) true else false
<console>:9: error: value name is not a member of                  res10: Boolean = true
Person                                                             scala> cp2.toString
    val m = p.name                                                 res13: String = CPerson(Jerry)

scala> p2.toString
res14: java.lang.String = Person@2cd0a9b2




This means that the Scala compiler adds factory method for case classes that eliminate need to add ‘new’ keyword.
Parameter list of case class are added as fields /members automatically .
Compiler also adds implementations of methods toString, hashCode, and equals to the case classes.

More Related Content

What's hot (19)

PDF
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kirill Rozov
 
PPTX
Scala Back to Basics: Type Classes
Tomer Gabel
 
PDF
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
PPT
Functional Programming In Java
Andrei Solntsev
 
PPT
Javascript arrays
Hassan Dar
 
KEY
Scala for ruby programmers
tymon Tobolski
 
PDF
ZIO Prelude - ZIO World 2021
Jorge Vásquez
 
PDF
Be Smart, Constrain Your Types to Free Your Brain!
Jorge Vásquez
 
PDF
Introduction to idris
Conor Farrell
 
PDF
学生向けScalaハンズオンテキスト part2
Opt Technologies
 
PDF
7 Habits For a More Functional Swift
Jason Larsen
 
PPTX
Joy of scala
Maxim Novak
 
PDF
Meet scala
Wojciech Pituła
 
PDF
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
PDF
A bit about Scala
Vladimir Parfinenko
 
PDF
学生向けScalaハンズオンテキスト
Opt Technologies
 
PPTX
Java script arrays
Frayosh Wadia
 
PDF
Scala 2013 review
Sagie Davidovich
 
PDF
High Wizardry in the Land of Scala
djspiewak
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kirill Rozov
 
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Functional Programming In Java
Andrei Solntsev
 
Javascript arrays
Hassan Dar
 
Scala for ruby programmers
tymon Tobolski
 
ZIO Prelude - ZIO World 2021
Jorge Vásquez
 
Be Smart, Constrain Your Types to Free Your Brain!
Jorge Vásquez
 
Introduction to idris
Conor Farrell
 
学生向けScalaハンズオンテキスト part2
Opt Technologies
 
7 Habits For a More Functional Swift
Jason Larsen
 
Joy of scala
Maxim Novak
 
Meet scala
Wojciech Pituła
 
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
A bit about Scala
Vladimir Parfinenko
 
学生向けScalaハンズオンテキスト
Opt Technologies
 
Java script arrays
Frayosh Wadia
 
Scala 2013 review
Sagie Davidovich
 
High Wizardry in the Land of Scala
djspiewak
 

Viewers also liked (7)

PDF
Advanced Scala
Fabian Becker
 
PDF
Seminar Joomla 1.5 SEF-Mechanismus
Fabian Becker
 
PDF
GNU Bourne Again SHell
Fabian Becker
 
ODP
Ruby
Fabian Becker
 
ODP
Case class scala
Matt Hicks
 
PDF
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Stanford GSB Corporate Governance Research Initiative
 
PDF
Hype vs. Reality: The AI Explainer
Luminary Labs
 
Advanced Scala
Fabian Becker
 
Seminar Joomla 1.5 SEF-Mechanismus
Fabian Becker
 
GNU Bourne Again SHell
Fabian Becker
 
Case class scala
Matt Hicks
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Stanford GSB Corporate Governance Research Initiative
 
Hype vs. Reality: The AI Explainer
Luminary Labs
 
Ad

Similar to Scala case of case classes (20)

PDF
Scala vs Java 8 in a Java 8 World
BTI360
 
PDF
Scala-对Java的修正和超越
Caoyuan Deng
 
PDF
Scala for Java Programmers
Eric Pederson
 
PDF
Scala taxonomy
Radim Pavlicek
 
PDF
Introducing Pattern Matching in Scala
Ayush Mishra
 
ODP
1.5 pattern matching
futurespective
 
PDF
Scala Paradigms
Tom Flaherty
 
ODP
Naïveté vs. Experience
Mike Fogus
 
PDF
What I learned from Seven Languages in Seven Weeks (IPRUG)
Kerry Buckley
 
PDF
Scala for Jedi
Vladimir Parfinenko
 
PDF
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest
 
PDF
Programming in scala - 1
Mukesh Kumar
 
ODP
2.1 recap from-day_one
futurespective
 
KEY
ddd+scala
潤一 加藤
 
PDF
Scala Bootcamp 1
Knoldus Inc.
 
ODP
Introducing scala
Meetu Maltiar
 
ODP
AST Transformations at JFokus
HamletDRC
 
PDF
ハイブリッド言語Scalaを使う
bpstudy
 
PDF
Introduction to Scala
Brian Hsu
 
PDF
A Scala tutorial
Dima Statz
 
Scala vs Java 8 in a Java 8 World
BTI360
 
Scala-对Java的修正和超越
Caoyuan Deng
 
Scala for Java Programmers
Eric Pederson
 
Scala taxonomy
Radim Pavlicek
 
Introducing Pattern Matching in Scala
Ayush Mishra
 
1.5 pattern matching
futurespective
 
Scala Paradigms
Tom Flaherty
 
Naïveté vs. Experience
Mike Fogus
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
Kerry Buckley
 
Scala for Jedi
Vladimir Parfinenko
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest
 
Programming in scala - 1
Mukesh Kumar
 
2.1 recap from-day_one
futurespective
 
ddd+scala
潤一 加藤
 
Scala Bootcamp 1
Knoldus Inc.
 
Introducing scala
Meetu Maltiar
 
AST Transformations at JFokus
HamletDRC
 
ハイブリッド言語Scalaを使う
bpstudy
 
Introduction to Scala
Brian Hsu
 
A Scala tutorial
Dima Statz
 
Ad

More from VulcanMinds (8)

PPTX
Dig up the gold in your godowns
VulcanMinds
 
PPTX
Mongo DB in Health Care Part 1
VulcanMinds
 
PPTX
Designing a play framework application
VulcanMinds
 
PPTX
Scala xml power play part 1
VulcanMinds
 
PPTX
Tupple ware in scala
VulcanMinds
 
PPTX
Scala elegant and exotic part 1
VulcanMinds
 
PPTX
Data choreography in mongo
VulcanMinds
 
PPTX
Munching the mongo
VulcanMinds
 
Dig up the gold in your godowns
VulcanMinds
 
Mongo DB in Health Care Part 1
VulcanMinds
 
Designing a play framework application
VulcanMinds
 
Scala xml power play part 1
VulcanMinds
 
Tupple ware in scala
VulcanMinds
 
Scala elegant and exotic part 1
VulcanMinds
 
Data choreography in mongo
VulcanMinds
 
Munching the mongo
VulcanMinds
 

Recently uploaded (20)

PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

Scala case of case classes

  • 1. Scala – Case of Case Classes By VulcanMinds
  • 2. Case Classes - Concepts Scala provides ‘Case Classes’ to do elegant comparisons in your code about the class object types. for e.g. a case class looks like… scala> abstract case class Animal defined class Animal scala> case class Dog(breed:String,name:String) extends Animal; defined class Dog scala> case class Cat(breed:String,name:String) extends Animal; defined class Cat Now Create instances…… scala> var anAnimal:Animal = new Cat(“Indonesian","Silly"); anAnimal: Animal = Animal() scala> var anAnimal2:Animal = new Dog("Alsatian","Biscuit"); anAnimal2: Animal = Animal() scala> anAnimal match { | case Cat(breed,name) => println("The animal was cat with name :" + name + “ and breed:" + breed) | case Dog(breed,name) => println("The animal was dog with name :" + name + “ and breed:" + breed)} The animal was cat with name :Silly and breed:Indonesian
  • 3. Case Classes - Concepts More examples..... scala> def anyGobbler(anyAnimal:Any) { | anyAnimal match { | case Dog(breed , name) => println("You gave me a Dog with value :" + anyAnimal); | case Cat(breed, name) => println("You gave me a Cat :" + anyAnimal); | case _ => println("Excuse me, why did you send me something " + anyAnimal); | }} anyGobbler: (anyAnimal: Any)Unit scala> var myDog:Dog = new Dog(“Alsatian",“biscuit") myDog: Dog = Animal() scala> var myCat:Cat = new Cat("indonesian","silly") myCat: Cat = Animal() scala> anyGobbler(myDog); You gave me a Dog with value :Animal() scala> anyGobbler(myCat); You gave me a Cat :Animal() scala> anyGobbler("garbage"); Excuse me, why did you send me something garbage
  • 4. Case Classes - Concepts Accessing the members of the case classes instances…. scala> def anyGobbler2(anyAnimal:Any) { | anyAnimal match { | case Dog(breed,name) => println("You gave me a Dog with breed ::" + breed + " with name:" + name); | case Cat(breed, name) => println("You gave me a Cat with breed:" + breed + " with name:" + name); | case _ => println("Excuse me, why did you give me something else" + anyAnimal); |} |} anyGobbler2: (anyAnimal: Any)Unit scala> anyGobbler2(new Dog("Alsatian","Biscuit")); You gave me a Dog with breed ::Alsatian with name: Biscuit scala> anyGobbler2(new Cat("Indonesian","Silly")); You gave me a Cat with breed:Indonesian with name :Silly Define a new animal anyGobble2 doesn’t know….. scala> class Mouse(type:String) extends Animal; defined class Mouse scala> anyGobbler2(new Mouse("JerryType")); Excuse me, why did you give me something else Animal()
  • 5. The apply() method You can define an apply(….) method for any Class or an Object and it will be called anytime you append a pair of parenthesis ‘( )’ to the object of that class. Like below scala> object Test { | def apply(x:Int) = { | x*5 } |} defined module Test Calling it is as below … scala> var a = Test(100) a: Int = 500} scala> class CTest { | def apply(x:Int) = { | x*5} |} defined class CTest scala> var s = new CTest s: CTest = CTest@5bbe2de2 scala> var p = s(100); p: Int = 500
  • 6. The unapply() method Similarly you also define an unapply(….) method for any Class or an Object and it will be called during a case match block of code as below… scala> object Test { | def unapply(x:Int):Option[Int] = { | if (x > 5) Some(x) else None} |} defined module Test scala> for(i <- 1 to 10) i match { | case Test(a) => println(" value of a " + a) | case _ => println("not matching")} not matching not matching not matching not matching not matching value of a 6 value of a 7 value of a 8 value of a 9 value of a 10
  • 7. class Vs case class scala> class Person(name:String) scala> case class CPerson(name:String) defined class Person defined class CPerson scala> val p = new Person("Tom") scala> var cp = CPerson("Jerry") p: Person = Person@362a7b cp: CPerson = CPerson(Jerry) scala> val p2 = new Person("Tom") scala> val n = cp.name p2: Person = Person@2cd0a9b2 n: String = Jerry scala> if(p == p2) true else false scala> var cp2 = CPerson("Jerry") res12: Boolean = false cp2: CPerson = CPerson(Jerry) scala> val m = p.name scala> if(cp == cp2) true else false <console>:9: error: value name is not a member of res10: Boolean = true Person scala> cp2.toString val m = p.name res13: String = CPerson(Jerry) scala> p2.toString res14: java.lang.String = Person@2cd0a9b2 This means that the Scala compiler adds factory method for case classes that eliminate need to add ‘new’ keyword. Parameter list of case class are added as fields /members automatically . Compiler also adds implementations of methods toString, hashCode, and equals to the case classes.