SlideShare a Scribd company logo
1 of 18
Download to read offline
Returning the
"Current" Type in Scala
http://tpolecat.github.io/
2015/04/29/f-bounds.html
1.
2.
Needs
.
..?
OOP .
trait Pet {
def name: String
def renamed(newName: String): Pet
}
case class Fish(name: String, age: Int) extends Pet {
def renamed(newName: String): Fish = copy(name = newName)
}
.
scala> val a = Fish("Jimmy", 2)
a: Fish = Fish(Jimmy,2)
// renamed Fish .
scala> val b = a.renamed("Bob")
b: Fish = Fish(Bob,2)
...
...
Trait Pet .
case class Kitty(name: String, color: Color) extends Pet {
def renamed(newName: String): Fish = new Fish(newName, 42) // oops
}
Oops, ...
The problem
• Trait renamed Pet Pet Fish
.
• . Compiler
.
• .
1. .
general .
def esquire[A <: Pet](a: A): A = a.renamed(a.name + ", Esq.")
<console>:28: error: type mismatch;
found : Pet
required: A
def esquire[A <: Pet](a: A): A = a.renamed(a.name + ", Esq.")
^
A <: Pet
. Pet .
2. F-Bounded Types
.
F-bounded typs type parameter
.
superclass .
Pet[A <: Pet[A]]
.
.
.
F-Bounded
trait Pet[A <: Pet[A]] {
def name: String
def renamed(newName: String): A // note this return type
}
A Pet renamed A .
Pet Trait .
Trait
.
.
case class Fish(name: String, age: Int) extends Pet[Fish] { // note the type argument
def renamed(newName: String) = copy(name = newName)
}
scala> val a = Fish("Jimmy", 2)
a: Fish = Fish(Jimmy,2)
scala> val b = a.renamed("Bob")
b: Fish = Fish(Bob,2)
// generic rename . Pet[A] renamed A .
scala> def esquire[A <: Pet[A]](a: A): A = a.renamed(a.name + ", Esq.")
esquire: [A <: Pet[A]](a: A)A
scala> esquire(a)
res8: Fish = Fish(Jimmy, Esq.,2)
...
.
case class Kitty(name: String, color: Color) extends Pet[Fish] { // oops
def renamed(newName: String): Fish = new Fish(newName, 42)
}
;;
self type annotation .
trait Pet[A <: Pet[A]] { this: A => // self-type
def name: String
def renamed(newName: String): A
}
self type annotation .
```scala
case class Kitty(name: String, color: Color) extends Pet[Fish] {
def renamed(newName: String): Fish = new Fish(newName, 42)
}
<console>:19: error: illegal inheritance;
self-type Kitty does not conform to Pet[Fish]'s selftype Fish
case class Kitty(name: String, color: Color) extends Pet[Fish] {
^
Fish Kitty
.
....
Pet class class .
class Mammal(val name: String) extends Pet[Mammal] {
def renamed(newName: String) = new Mammal(newName)
}
class Monkey(name: String) extends Mammal(name) // hmm, Monkey is a Pet[Mammal]
res0: Mammal = Mammal@5587afd3
!
OTL
Typeclass ?
Pet rename typeclass .
trait Pet {
def name: String
}
// rename Pet
trait Rename[A] {
def rename(a: A, newName: String): A
}
Typeclass
case class Fish(name: String, age: Int) extends Pet
object Fish {
// Fish rename Rename Trait .
implicit val FishRename = new Rename[Fish] {
def renamed(a: Fish, newName: String) = a.copy(name = newName)
}
}
Typeclass implicit class
implicit class Pet rename
.
implicit class RenameOps[A](a: A)(implicit ev: Rename[A]) {
def renamed(newName: String) = ev.renamed(a, newName)
}
scala> val a = Fish("Jimmy", 2)
a: Fish = Fish(Jimmy,2)
scala> val b = a.renamed("Bob")
b: Fish = Fish(Bob,2)
// F bounded
scala> def esquire[A <: Pet : Rename](a: A): A = a.renamed(a.name + ", Esq.")
esquire: [A <: Pet](a: A)(implicit evidence$1: Rename[A])A
scala> esquire(a)
res10: Fish = Fish(Jimmy, Esq.,2)
syntax
.
Typeclass ?
! ad-hoc polymorphism
trait Pet[A] {
def name(a: A): String
def renamed(a: A, newName: String): A
}
implicit class PetOps[A](a: A)(implicit ev: Pet[A]) {
def name = ev.name(a)
def renamed(newName: String): A = ev.renamed(a, newName)
}
!
case class Fish(name: String, age: Int)
object Fish {
implicit val FishPet = new Pet[Fish] {
def name(a: Fish) = a.name
def renamed(a: Fish, newName: String) = a.copy(name = newName)
}
}
// renamed `PetOps` .
scala> Fish("Bob", 42).renamed("Steve")
res0: Fish = Fish(Steve,42)

More Related Content

What's hot

Haskell - Being lazy with class
Haskell - Being lazy with classHaskell - Being lazy with class
Haskell - Being lazy with classTiago Babo
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: DeanonymizingDavid Evans
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slidejonycse
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Danial Virk
 
Soirée Guava et Lombok avec Thierry Leriche
Soirée Guava et Lombok avec Thierry LericheSoirée Guava et Lombok avec Thierry Leriche
Soirée Guava et Lombok avec Thierry LericheNormandy JUG
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)Kerry Buckley
 
Milou fait un régime Guava Lombok
Milou fait un régime Guava LombokMilou fait un régime Guava Lombok
Milou fait un régime Guava LombokLorraine JUG
 
201209 Lombok & Guava
201209 Lombok & Guava201209 Lombok & Guava
201209 Lombok & Guavalyonjug
 
From Python to Scala
From Python to ScalaFrom Python to Scala
From Python to ScalaFFunction inc
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
 
OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010bturnbull
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersMichael Galpin
 
Computación evolutiva en Perl
Computación evolutiva en PerlComputación evolutiva en Perl
Computación evolutiva en PerlJuan J. Merelo
 

What's hot (20)

Haskell - Being lazy with class
Haskell - Being lazy with classHaskell - Being lazy with class
Haskell - Being lazy with class
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: Deanonymizing
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
Soirée Guava et Lombok avec Thierry Leriche
Soirée Guava et Lombok avec Thierry LericheSoirée Guava et Lombok avec Thierry Leriche
Soirée Guava et Lombok avec Thierry Leriche
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
 
Milou fait un régime Guava Lombok
Milou fait un régime Guava LombokMilou fait un régime Guava Lombok
Milou fait un régime Guava Lombok
 
201209 Lombok & Guava
201209 Lombok & Guava201209 Lombok & Guava
201209 Lombok & Guava
 
From Python to Scala
From Python to ScalaFrom Python to Scala
From Python to Scala
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Prolog
PrologProlog
Prolog
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010OOP Intro in Ruby for NHRuby Feb 2010
OOP Intro in Ruby for NHRuby Feb 2010
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Computación evolutiva en Perl
Computación evolutiva en PerlComputación evolutiva en Perl
Computación evolutiva en Perl
 

Similar to F bound-types

Object Calisthenics Refactoring Dojo
Object Calisthenics Refactoring DojoObject Calisthenics Refactoring Dojo
Object Calisthenics Refactoring DojoMike Long
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaVasil Remeniuk
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classesmaznabili
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
Oops implemetation material
Oops implemetation materialOops implemetation material
Oops implemetation materialDeepak Solanki
 
Imagine that you want to keep track of your pet fish. Each fish is a.pdf
Imagine that you want to keep track of your pet fish. Each fish is a.pdfImagine that you want to keep track of your pet fish. Each fish is a.pdf
Imagine that you want to keep track of your pet fish. Each fish is a.pdfbadshetoms
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala LanguageAshal aka JOKER
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 

Similar to F bound-types (9)

Object Calisthenics Refactoring Dojo
Object Calisthenics Refactoring DojoObject Calisthenics Refactoring Dojo
Object Calisthenics Refactoring Dojo
 
Fast Forward To Scala
Fast Forward To ScalaFast Forward To Scala
Fast Forward To Scala
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Oops implemetation material
Oops implemetation materialOops implemetation material
Oops implemetation material
 
Imagine that you want to keep track of your pet fish. Each fish is a.pdf
Imagine that you want to keep track of your pet fish. Each fish is a.pdfImagine that you want to keep track of your pet fish. Each fish is a.pdf
Imagine that you want to keep track of your pet fish. Each fish is a.pdf
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

F bound-types

  • 4. OOP . trait Pet { def name: String def renamed(newName: String): Pet } case class Fish(name: String, age: Int) extends Pet { def renamed(newName: String): Fish = copy(name = newName) }
  • 5. . scala> val a = Fish("Jimmy", 2) a: Fish = Fish(Jimmy,2) // renamed Fish . scala> val b = a.renamed("Bob") b: Fish = Fish(Bob,2) ...
  • 6. ... Trait Pet . case class Kitty(name: String, color: Color) extends Pet { def renamed(newName: String): Fish = new Fish(newName, 42) // oops } Oops, ...
  • 7. The problem • Trait renamed Pet Pet Fish . • . Compiler . • .
  • 8. 1. . general . def esquire[A <: Pet](a: A): A = a.renamed(a.name + ", Esq.") <console>:28: error: type mismatch; found : Pet required: A def esquire[A <: Pet](a: A): A = a.renamed(a.name + ", Esq.") ^ A <: Pet . Pet .
  • 9. 2. F-Bounded Types . F-bounded typs type parameter . superclass . Pet[A <: Pet[A]] . . .
  • 10. F-Bounded trait Pet[A <: Pet[A]] { def name: String def renamed(newName: String): A // note this return type } A Pet renamed A . Pet Trait . Trait .
  • 11. . case class Fish(name: String, age: Int) extends Pet[Fish] { // note the type argument def renamed(newName: String) = copy(name = newName) } scala> val a = Fish("Jimmy", 2) a: Fish = Fish(Jimmy,2) scala> val b = a.renamed("Bob") b: Fish = Fish(Bob,2) // generic rename . Pet[A] renamed A . scala> def esquire[A <: Pet[A]](a: A): A = a.renamed(a.name + ", Esq.") esquire: [A <: Pet[A]](a: A)A scala> esquire(a) res8: Fish = Fish(Jimmy, Esq.,2)
  • 12. ... . case class Kitty(name: String, color: Color) extends Pet[Fish] { // oops def renamed(newName: String): Fish = new Fish(newName, 42) } ;;
  • 13. self type annotation . trait Pet[A <: Pet[A]] { this: A => // self-type def name: String def renamed(newName: String): A } self type annotation . ```scala case class Kitty(name: String, color: Color) extends Pet[Fish] { def renamed(newName: String): Fish = new Fish(newName, 42) } <console>:19: error: illegal inheritance; self-type Kitty does not conform to Pet[Fish]'s selftype Fish case class Kitty(name: String, color: Color) extends Pet[Fish] { ^ Fish Kitty .
  • 14. .... Pet class class . class Mammal(val name: String) extends Pet[Mammal] { def renamed(newName: String) = new Mammal(newName) } class Monkey(name: String) extends Mammal(name) // hmm, Monkey is a Pet[Mammal] res0: Mammal = Mammal@5587afd3 ! OTL
  • 15. Typeclass ? Pet rename typeclass . trait Pet { def name: String } // rename Pet trait Rename[A] { def rename(a: A, newName: String): A }
  • 16. Typeclass case class Fish(name: String, age: Int) extends Pet object Fish { // Fish rename Rename Trait . implicit val FishRename = new Rename[Fish] { def renamed(a: Fish, newName: String) = a.copy(name = newName) } }
  • 17. Typeclass implicit class implicit class Pet rename . implicit class RenameOps[A](a: A)(implicit ev: Rename[A]) { def renamed(newName: String) = ev.renamed(a, newName) } scala> val a = Fish("Jimmy", 2) a: Fish = Fish(Jimmy,2) scala> val b = a.renamed("Bob") b: Fish = Fish(Bob,2) // F bounded scala> def esquire[A <: Pet : Rename](a: A): A = a.renamed(a.name + ", Esq.") esquire: [A <: Pet](a: A)(implicit evidence$1: Rename[A])A scala> esquire(a) res10: Fish = Fish(Jimmy, Esq.,2) syntax .
  • 18. Typeclass ? ! ad-hoc polymorphism trait Pet[A] { def name(a: A): String def renamed(a: A, newName: String): A } implicit class PetOps[A](a: A)(implicit ev: Pet[A]) { def name = ev.name(a) def renamed(newName: String): A = ev.renamed(a, newName) } ! case class Fish(name: String, age: Int) object Fish { implicit val FishPet = new Pet[Fish] { def name(a: Fish) = a.name def renamed(a: Fish, newName: String) = a.copy(name = newName) } } // renamed `PetOps` . scala> Fish("Bob", 42).renamed("Steve") res0: Fish = Fish(Steve,42)