SlideShare a Scribd company logo
1 of 7
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

Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmerstymon Tobolski
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021Jorge Vásquez
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idrisConor Farrell
 
学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2Opt Technologies
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキストOpt Technologies
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 

What's hot (19)

Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
Introduction to idris
Introduction to idrisIntroduction to idris
Introduction to idris
 
学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 

Viewers also liked

Viewers also liked (7)

Advanced Scala
Advanced ScalaAdvanced Scala
Advanced Scala
 
Seminar Joomla 1.5 SEF-Mechanismus
Seminar Joomla 1.5 SEF-MechanismusSeminar Joomla 1.5 SEF-Mechanismus
Seminar Joomla 1.5 SEF-Mechanismus
 
GNU Bourne Again SHell
GNU Bourne Again SHellGNU Bourne Again SHell
GNU Bourne Again SHell
 
Ruby
RubyRuby
Ruby
 
Case class scala
Case class scalaCase class scala
Case class scala
 
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job? Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
Succession “Losers”: What Happens to Executives Passed Over for the CEO Job?
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 

Similar to Scala case of case classes

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
42.type: Literal-based Singleton types
42.type: Literal-based Singleton types42.type: Literal-based Singleton types
42.type: Literal-based Singleton typesGeorge Leontiev
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8bryanbibat
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesCody Yun
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02Nguyen Tuan
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)William Narmontas
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 

Similar to Scala case of case classes (20)

Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
42.type: Literal-based Singleton types
42.type: Literal-based Singleton types42.type: Literal-based Singleton types
42.type: Literal-based Singleton types
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala 101
Scala 101Scala 101
Scala 101
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and Classes
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 

More from VulcanMinds

Dig up the gold in your godowns
Dig up the gold in your godownsDig up the gold in your godowns
Dig up the gold in your godownsVulcanMinds
 
Mongo DB in Health Care Part 1
Mongo DB in Health Care Part 1Mongo DB in Health Care Part 1
Mongo DB in Health Care Part 1VulcanMinds
 
Designing a play framework application
Designing a play framework applicationDesigning a play framework application
Designing a play framework applicationVulcanMinds
 
Scala xml power play part 1
Scala   xml power play part 1Scala   xml power play part 1
Scala xml power play part 1VulcanMinds
 
Tupple ware in scala
Tupple ware in scalaTupple ware in scala
Tupple ware in scalaVulcanMinds
 
Scala elegant and exotic part 1
Scala  elegant and exotic part 1Scala  elegant and exotic part 1
Scala elegant and exotic part 1VulcanMinds
 
Data choreography in mongo
Data choreography in mongoData choreography in mongo
Data choreography in mongoVulcanMinds
 
Munching the mongo
Munching the mongoMunching the mongo
Munching the mongoVulcanMinds
 

More from VulcanMinds (8)

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

Recently uploaded

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 

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.