SlideShare uma empresa Scribd logo
1 de 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.

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

Case class scala
Case class scalaCase class scala
Case class scala
Matt Hicks
 

Destaque (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
 

Semelhante a Scala case of case classes

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
 
(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
 

Semelhante a 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
 

Mais de 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
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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.