SlideShare una empresa de Scribd logo
1 de 24
TYPE CLASSES
Ad-Hoc Polymorphismus ohne Unterklassen




       Scala User Group Köln/Bonn
                @scalacgn
                    1
POLYMORPHISMUS




       2
POLYMORPHISMUS
• Parametrisiert

  • Generische   Funktionen und Datentypen




                           2
POLYMORPHISMUS
• Parametrisiert

  • Generische   Funktionen und Datentypen

• Ad-hoc

  • Methoden-    und Operator-Overloading

  • Unterklassen     (Subtype Polymorphismus)

  • Type   Classes

                              2
CASE CLASSES SERIALISIEREN
 package model {
   case class Person(firstName: String, lastName: String)
   case class Restaurant(name: String, address: String)
 }




                                                            3
CASE CLASSES SERIALISIEREN
 package model {
   case class Person(firstName: String, lastName: String)
   case class Restaurant(name: String, address: String)
 }



                                                                         Neue
                             JSON                     CSV       XML
                                                                        Funktion
      Person                 toJson                 toCsv       toXml

     Restaurant              toJson                 toCsv       toXml

     Neuer Typ


                                                            3
ÜBERLADEN
1. object JsonSerializer {
2.   def toJson(person: Person): String = """{ name : "%s %s" }""".format(person.firstName, person.lastName)
3.   def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
4. }
5.  
6. object CsvSerializer {
7.   def toCSV(person: Person): String = "%s,%s".format(person.firstName, person.lastName)
8.   def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address)
9. }




                                                       4
ÜBERLADEN
1. object JsonSerializer {
2.   def toJson(person: Person): String = """{ name : "%s %s" }""".format(person.firstName, person.lastName)
3.   def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
4. }
5.  
6. object CsvSerializer {
7.   def toCSV(person: Person): String = "%s,%s".format(person.firstName, person.lastName)
8.   def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address)
9. }




       +Einfach
       - Kein Zusammenhang außer Methodenname




                                                       4
UNTERKLASSEN
1. abstract class Serializer {
2.   def toJson: String
3.   def toCSV: String
4. }
5.  
6. case class Person(firstName: String, lastName: String) extends Serializer {
7.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName)
8.   override def toCSV: String = "%s,%s".format(firstName, lastName)
9. }
10.  
11. case class Restaurant(name: String, address: String) extends Serializer {
12.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
13.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address)
14. }


1. import models._
2. Person("Max", "Mustermann").toJson




                                                        5
UNTERKLASSEN
1. abstract class Serializer {
2.   def toJson: String
3.   def toCSV: String
4. }
5.  
6. case class Person(firstName: String, lastName: String) extends Serializer {
7.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName)
8.   override def toCSV: String = "%s,%s".format(firstName, lastName)
9. }
10.  
11. case class Restaurant(name: String, address: String) extends Serializer {
12.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
13.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address)
14. }


1. import models._
2. Person("Max", "Mustermann").toJson




+ Einfach neue Klassen hinzuzufügen
- Modellklassen müssen von Serializer ableiten

                                                        5
TRAITS
1. trait JsonSerializer {
2.   def toJson: String
3. }
4.  
5. trait CsvSerializer {
6.   def toCSV: String
7. }
8.  
9. case class Person(firstName: String, lastName: String) extends JsonSerializer with CsvSerializer {
10.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName)
11.   override def toCSV: String = "%s,%s".format(firstName, lastName)
12. }
13.  
14. case class Restaurant(name: String, address: String)  extends JsonSerializer with CsvSerializer {
15.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
16.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address)
17. }




                                                        6
TRAITS
1. trait JsonSerializer {
2.   def toJson: String
3. }
4.  
5. trait CsvSerializer {
6.   def toCSV: String
7. }
8.  
9. case class Person(firstName: String, lastName: String) extends JsonSerializer with CsvSerializer {
10.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName)
11.   override def toCSV: String = "%s,%s".format(firstName, lastName)
12. }
13.  
14. case class Restaurant(name: String, address: String)  extends JsonSerializer with CsvSerializer {
15.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
16.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address)
17. }




- Serialisieren hat nichts mit der Logik zu tun,
  Code steht nicht immer zur Verfügung

                                                        6
TYPE CASING
1. object JsonSerializer {
2.   def toJson(x: AnyRef): String = x match {
3.     case person: Person => """{ name : "%s %s" }""".format(person.firstName, person.lastName)
4.     case r: Restaurant => """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
5.   }
6.  
7. object CsvSerializer {
8.   def toCSV(x: AnyRef): String = x match {
9.     case person: Person => "%s,%s".format(person.firstName, person.lastName)
10.     case r: Restaurant => "%s,%s".format(r.name, r.address)
11.   }
12. }




                                                        7
TYPE CASING
1. object JsonSerializer {
2.   def toJson(x: AnyRef): String = x match {
3.     case person: Person => """{ name : "%s %s" }""".format(person.firstName, person.lastName)
4.     case r: Restaurant => """{ name : "%s"; address: "%s" }""".format(r.name, r.address)
5.   }
6.  
7. object CsvSerializer {
8.   def toCSV(x: AnyRef): String = x match {
9.     case person: Person => "%s,%s".format(person.firstName, person.lastName)
10.     case r: Restaurant => "%s,%s".format(r.name, r.address)
11.   }
12. }




+ Einfach neue Funktionen hinzuzufügen
- Viele Eingriffe bei neuem Typ



                                                        7
TYPE CLASSES (1)
1. package serializer
2.  
3. trait CsvSerializable[T] {
4.   def toCsv(t: T): String
5. }
6.  
7. object CsvSerializable {
8.   import models._
9.  
10.   def toCsv[T](t: T)(implicit serializer: CsvSerializable[T]): String =
11.     serializer.toCsv(t)
12.  
13.   implicit object UserSerializable extends CsvSerializable[Person] {
14.     def toCsv(person: User) String =
15.       "%s,%s".format(person.firstName, person.lastName)
16.   }
17. }



1. import serializer._
2. val user = User(name = "Max Musterbro")
3. val csvHelper = implicitly[CsvSerializable[User]]
4. csvHelper.toCsv(user)
5.  
6. // Oder
7. import serializer.CsvSerializable._
8. toCsv(User(name = "Max Musterbro"))

                                                        8
TYPE CLASSES (2)
1. trait JsonSerializable[T] {
2.   def toJson(t: T): String
3. }
4.  
5. object JsonSerializable {
6.   import models._
7.  
8.   implicit object UserSerializable extends JsonSerializable[Person] {
9.     def toJson(person: Person): String =
10.       """{ name : "%s", status: "%s" }""".format(person.firstName, person.lastName)
11.   }
12.  
13.   class UserSerializer(p: Person) {
14.     def toJson: String = UserSerializable.toJson(p)
15.   }
16.  
17.   implicit def UserToSerializer(p: Person) = new UserSerializer(p)


 1. import serializer.JsonSerializable._
 2. User(name = "Max Musterbro").toJson




                                                          9
TYPE CLASSES (3)




        10
TYPE CLASSES (3)
• Definition




                      10
TYPE CLASSES (3)
• Definition

 • Trait   mit Parameter




                           10
TYPE CLASSES (3)
• Definition

 • Trait   mit Parameter

 • Companion     Object mit Default Implementationen




                                10
TYPE CLASSES (3)
• Definition

  • Trait   mit Parameter

  • Companion      Object mit Default Implementationen

• Beispiele   in Scala: scala.math.Ordering und scala.math.Numeric




                                   10
TYPE CLASSES (3)
• Definition

  • Trait   mit Parameter

  • Companion      Object mit Default Implementationen

• Beispiele   in Scala: scala.math.Ordering und scala.math.Numeric

•+   Gut erweiterbar



                                   10
TYPE CLASSES (3)
• Definition

  • Trait   mit Parameter

  • Companion      Object mit Default Implementationen

• Beispiele   in Scala: scala.math.Ordering und scala.math.Numeric

•+   Gut erweiterbar
• - Viel   Code, implicits manchmal undurchsichtig

                                   10
> CODE

• https://twitter.com/scalacgn

• http://xing.to/scala




                                 11

Más contenido relacionado

Similar a Type Classes in Scala

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 ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecordscalaconfjp
 
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
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185Mahmoud Samir Fayed
 
Paradigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaParadigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaBruno Oliveira
 
Introduction to the Ruby Object Model
Introduction to the Ruby Object ModelIntroduction to the Ruby Object Model
Introduction to the Ruby Object ModelMiki Shiran
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesEelco Visser
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88Mahmoud Samir Fayed
 
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
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 

Similar a Type Classes in Scala (20)

Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
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
 
Php e Cassandra
Php e Cassandra Php e Cassandra
Php e Cassandra
 
Scala ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecord
 
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?
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185The Ring programming language version 1.5.4 book - Part 44 of 185
The Ring programming language version 1.5.4 book - Part 44 of 185
 
Paradigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaParadigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scala
 
Introduction to the Ruby Object Model
Introduction to the Ruby Object ModelIntroduction to the Ruby Object Model
Introduction to the Ruby Object Model
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88The Ring programming language version 1.3 book - Part 34 of 88
The Ring programming language version 1.3 book - Part 34 of 88
 
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
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 

Último

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
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
 
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 challengesrafiqahmad00786416
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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...Zilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
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 2024The Digital Insurer
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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)
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 

Type Classes in Scala

  • 1. TYPE CLASSES Ad-Hoc Polymorphismus ohne Unterklassen Scala User Group Köln/Bonn @scalacgn 1
  • 3. POLYMORPHISMUS • Parametrisiert • Generische Funktionen und Datentypen 2
  • 4. POLYMORPHISMUS • Parametrisiert • Generische Funktionen und Datentypen • Ad-hoc • Methoden- und Operator-Overloading • Unterklassen (Subtype Polymorphismus) • Type Classes 2
  • 5. CASE CLASSES SERIALISIEREN package model {   case class Person(firstName: String, lastName: String)   case class Restaurant(name: String, address: String) } 3
  • 6. CASE CLASSES SERIALISIEREN package model {   case class Person(firstName: String, lastName: String)   case class Restaurant(name: String, address: String) } Neue JSON CSV XML Funktion Person toJson toCsv toXml Restaurant toJson toCsv toXml Neuer Typ 3
  • 7. ÜBERLADEN 1. object JsonSerializer { 2.   def toJson(person: Person): String = """{ name : "%s %s" }""".format(person.firstName, person.lastName) 3.   def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 4. } 5.   6. object CsvSerializer { 7.   def toCSV(person: Person): String = "%s,%s".format(person.firstName, person.lastName) 8.   def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address) 9. } 4
  • 8. ÜBERLADEN 1. object JsonSerializer { 2.   def toJson(person: Person): String = """{ name : "%s %s" }""".format(person.firstName, person.lastName) 3.   def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 4. } 5.   6. object CsvSerializer { 7.   def toCSV(person: Person): String = "%s,%s".format(person.firstName, person.lastName) 8.   def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address) 9. } +Einfach - Kein Zusammenhang außer Methodenname 4
  • 9. UNTERKLASSEN 1. abstract class Serializer { 2.   def toJson: String 3.   def toCSV: String 4. } 5.   6. case class Person(firstName: String, lastName: String) extends Serializer { 7.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName) 8.   override def toCSV: String = "%s,%s".format(firstName, lastName) 9. } 10.   11. case class Restaurant(name: String, address: String) extends Serializer { 12.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 13.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address) 14. } 1. import models._ 2. Person("Max", "Mustermann").toJson 5
  • 10. UNTERKLASSEN 1. abstract class Serializer { 2.   def toJson: String 3.   def toCSV: String 4. } 5.   6. case class Person(firstName: String, lastName: String) extends Serializer { 7.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName) 8.   override def toCSV: String = "%s,%s".format(firstName, lastName) 9. } 10.   11. case class Restaurant(name: String, address: String) extends Serializer { 12.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 13.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address) 14. } 1. import models._ 2. Person("Max", "Mustermann").toJson + Einfach neue Klassen hinzuzufügen - Modellklassen müssen von Serializer ableiten 5
  • 11. TRAITS 1. trait JsonSerializer { 2.   def toJson: String 3. } 4.   5. trait CsvSerializer { 6.   def toCSV: String 7. } 8.   9. case class Person(firstName: String, lastName: String) extends JsonSerializer with CsvSerializer { 10.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName) 11.   override def toCSV: String = "%s,%s".format(firstName, lastName) 12. } 13.   14. case class Restaurant(name: String, address: String)  extends JsonSerializer with CsvSerializer { 15.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 16.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address) 17. } 6
  • 12. TRAITS 1. trait JsonSerializer { 2.   def toJson: String 3. } 4.   5. trait CsvSerializer { 6.   def toCSV: String 7. } 8.   9. case class Person(firstName: String, lastName: String) extends JsonSerializer with CsvSerializer { 10.   override def toJson: String = """{ name : "%s %s" }""".format(firstName, lastName) 11.   override def toCSV: String = "%s,%s".format(firstName, lastName) 12. } 13.   14. case class Restaurant(name: String, address: String)  extends JsonSerializer with CsvSerializer { 15.   override def toJson(r: Restaurant) = """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 16.   override def toCSV(r: Restaurant): String = "%s,%s".format(r.name, r.address) 17. } - Serialisieren hat nichts mit der Logik zu tun, Code steht nicht immer zur Verfügung 6
  • 13. TYPE CASING 1. object JsonSerializer { 2.   def toJson(x: AnyRef): String = x match { 3.     case person: Person => """{ name : "%s %s" }""".format(person.firstName, person.lastName) 4.     case r: Restaurant => """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 5.   } 6.   7. object CsvSerializer { 8.   def toCSV(x: AnyRef): String = x match { 9.     case person: Person => "%s,%s".format(person.firstName, person.lastName) 10.     case r: Restaurant => "%s,%s".format(r.name, r.address) 11.   } 12. } 7
  • 14. TYPE CASING 1. object JsonSerializer { 2.   def toJson(x: AnyRef): String = x match { 3.     case person: Person => """{ name : "%s %s" }""".format(person.firstName, person.lastName) 4.     case r: Restaurant => """{ name : "%s"; address: "%s" }""".format(r.name, r.address) 5.   } 6.   7. object CsvSerializer { 8.   def toCSV(x: AnyRef): String = x match { 9.     case person: Person => "%s,%s".format(person.firstName, person.lastName) 10.     case r: Restaurant => "%s,%s".format(r.name, r.address) 11.   } 12. } + Einfach neue Funktionen hinzuzufügen - Viele Eingriffe bei neuem Typ 7
  • 15. TYPE CLASSES (1) 1. package serializer 2.   3. trait CsvSerializable[T] { 4.   def toCsv(t: T): String 5. } 6.   7. object CsvSerializable { 8.   import models._ 9.   10.   def toCsv[T](t: T)(implicit serializer: CsvSerializable[T]): String = 11.     serializer.toCsv(t) 12.   13.   implicit object UserSerializable extends CsvSerializable[Person] { 14.     def toCsv(person: User) String = 15.       "%s,%s".format(person.firstName, person.lastName) 16.   } 17. } 1. import serializer._ 2. val user = User(name = "Max Musterbro") 3. val csvHelper = implicitly[CsvSerializable[User]] 4. csvHelper.toCsv(user) 5.   6. // Oder 7. import serializer.CsvSerializable._ 8. toCsv(User(name = "Max Musterbro")) 8
  • 16. TYPE CLASSES (2) 1. trait JsonSerializable[T] { 2.   def toJson(t: T): String 3. } 4.   5. object JsonSerializable { 6.   import models._ 7.   8.   implicit object UserSerializable extends JsonSerializable[Person] { 9.     def toJson(person: Person): String = 10. """{ name : "%s", status: "%s" }""".format(person.firstName, person.lastName) 11.   } 12.   13.   class UserSerializer(p: Person) { 14.     def toJson: String = UserSerializable.toJson(p) 15.   } 16.   17.   implicit def UserToSerializer(p: Person) = new UserSerializer(p) 1. import serializer.JsonSerializable._ 2. User(name = "Max Musterbro").toJson 9
  • 18. TYPE CLASSES (3) • Definition 10
  • 19. TYPE CLASSES (3) • Definition • Trait mit Parameter 10
  • 20. TYPE CLASSES (3) • Definition • Trait mit Parameter • Companion Object mit Default Implementationen 10
  • 21. TYPE CLASSES (3) • Definition • Trait mit Parameter • Companion Object mit Default Implementationen • Beispiele in Scala: scala.math.Ordering und scala.math.Numeric 10
  • 22. TYPE CLASSES (3) • Definition • Trait mit Parameter • Companion Object mit Default Implementationen • Beispiele in Scala: scala.math.Ordering und scala.math.Numeric •+ Gut erweiterbar 10
  • 23. TYPE CLASSES (3) • Definition • Trait mit Parameter • Companion Object mit Default Implementationen • Beispiele in Scala: scala.math.Ordering und scala.math.Numeric •+ Gut erweiterbar • - Viel Code, implicits manchmal undurchsichtig 10

Notas del editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n