SlideShare ist ein Scribd-Unternehmen logo
1 von 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.

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 

Kürzlich hochgeladen (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 

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.