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

Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
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
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 

Recently uploaded (20)

Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
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
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 

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)