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.
Ad

More Related Content

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
Kirill Rozov
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
Andrei Solntsev
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
Hassan Dar
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
tymon Tobolski
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
Jorge 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 idris
Conor Farrell
 
学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2
Opt 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 Swift
Jason Larsen
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
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
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
Vladimir Parfinenko
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
Opt Technologies
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
Frayosh Wadia
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
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
djspiewak
 
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
Kirill Rozov
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
Andrei Solntsev
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
Hassan Dar
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
tymon Tobolski
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
Jorge 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 idris
Conor Farrell
 
学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2学生向けScalaハンズオンテキスト part2
学生向けScalaハンズオンテキスト part2
Opt 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 Swift
Jason 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 Scala
djspiewak
 

Viewers also liked (7)

Advanced Scala
Advanced ScalaAdvanced Scala
Advanced Scala
Fabian Becker
 
Seminar Joomla 1.5 SEF-Mechanismus
Seminar Joomla 1.5 SEF-MechanismusSeminar Joomla 1.5 SEF-Mechanismus
Seminar Joomla 1.5 SEF-Mechanismus
Fabian Becker
 
GNU Bourne Again SHell
GNU Bourne Again SHellGNU Bourne Again SHell
GNU Bourne Again SHell
Fabian Becker
 
Ruby
RubyRuby
Ruby
Fabian Becker
 
Case class scala
Case class scalaCase class scala
Case class scala
Matt Hicks
 
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?
Stanford GSB Corporate Governance Research Initiative
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
Luminary Labs
 
Ad

Similar to Scala case of case classes (20)

Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
Radim Pavlicek
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
intelliyole
 
42.type: Literal-based Singleton types
42.type: Literal-based Singleton types42.type: Literal-based Singleton types
42.type: Literal-based Singleton types
George Leontiev
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
bryanbibat
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Scala 101
Scala 101Scala 101
Scala 101
Andrey Myatlyuk
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi 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 Classes
Cody Yun
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
潤一 加藤
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
bpstudy
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Lorenzo Dematté
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen Tuan
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
William Narmontas
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
futurespective
 
(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
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
Rémy-Christophe Schermesser
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
intelliyole
 
42.type: Literal-based Singleton types
42.type: Literal-based Singleton types42.type: Literal-based Singleton types
42.type: Literal-based Singleton types
George Leontiev
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
bryanbibat
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi 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 Classes
Cody Yun
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
bpstudy
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen 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
 
Ad

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
VulcanMinds
 
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
VulcanMinds
 
Designing a play framework application
Designing a play framework applicationDesigning a play framework application
Designing a play framework application
VulcanMinds
 
Scala xml power play part 1
Scala   xml power play part 1Scala   xml power play part 1
Scala xml power play part 1
VulcanMinds
 
Tupple ware in scala
Tupple ware in scalaTupple ware in scala
Tupple ware in scala
VulcanMinds
 
Scala elegant and exotic part 1
Scala  elegant and exotic part 1Scala  elegant and exotic part 1
Scala elegant and exotic part 1
VulcanMinds
 
Data choreography in mongo
Data choreography in mongoData choreography in mongo
Data choreography in mongo
VulcanMinds
 
Munching the mongo
Munching the mongoMunching the mongo
Munching the mongo
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 godowns
VulcanMinds
 
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
VulcanMinds
 
Designing a play framework application
Designing a play framework applicationDesigning a play framework application
Designing a play framework application
VulcanMinds
 
Scala xml power play part 1
Scala   xml power play part 1Scala   xml power play part 1
Scala xml power play part 1
VulcanMinds
 
Tupple ware in scala
Tupple ware in scalaTupple ware in scala
Tupple ware in scala
VulcanMinds
 
Scala elegant and exotic part 1
Scala  elegant and exotic part 1Scala  elegant and exotic part 1
Scala elegant and exotic part 1
VulcanMinds
 
Data choreography in mongo
Data choreography in mongoData choreography in mongo
Data choreography in mongo
VulcanMinds
 
Munching the mongo
Munching the mongoMunching the mongo
Munching the mongo
VulcanMinds
 

Recently uploaded (20)

machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 

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.