Forked from odersky/A simpler way to returning the "current" type in Scala.
Last active
August 29, 2015 14:20
-
-
Save mushtaq/82fd1b3743b8f106277d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** This is in reference to @tploecat's blog http://tpolecat.github.io/2015/04/29/f-bounds.html | |
* where he compares F-bounded polymorphism and type classes for implementing "MyType". | |
* | |
* Curiously, the in my mind obvious solution is missing: Use abstract types. | |
* | |
* A lot of this material, including an argument against F-bounded for the use-case | |
* is discussed in: | |
* | |
* Kim B. Bruce, Martin Odersky, Philip Wadler: | |
* A Statically Safe Alternative to Virtual Types. ECOOP 1998: 523-549 | |
*/ | |
trait Pet { | |
type This <: Pet | |
def name: String | |
def renamed(newName: String): This | |
} | |
case class Fish(name: String, age: Int) extends Pet { | |
type This = Fish | |
def renamed(newName: String): Fish = copy(name = newName) | |
} | |
case class Kitty(name: String, age: Int) extends Pet { | |
type This = Kitty | |
def renamed(newName: String): Kitty = copy(name = newName) | |
} | |
object Test { | |
def esquire[A <: Pet](a: A): a.This = a.renamed(a.name + ", Esq.") | |
val f: Fish = esquire(new Fish("bob", 22)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment