Skip to content

Instantly share code, notes, and snippets.

@jrudolph
Created June 27, 2011 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrudolph/1048906 to your computer and use it in GitHub Desktop.
Save jrudolph/1048906 to your computer and use it in GitHub Desktop.
Existentials considered harmful
object ExistentialsConsideredHarmful {
class Animal(val name: String)
object Dog extends Animal("Dog")
object Sheep extends Animal("Sheep")
trait Tools[A] {
def shave(a: A): A
}
def tools[A](a: A): Tools[A] = null // dummy
case class TransportBox[A <: Animal](animal: A, tools: Tools[A]) {
def label: String = animal.name
}
// 1.
def carry(box: TransportBox[_]): Unit = {
println(box.animal.name+" got carried away")
}
val aBox =
if (math.random < 0.5)
TransportBox(Dog, tools(Dog))
else
TransportBox(Sheep, tools(Sheep))
// 2.
aBox.tools.shave(aBox.animal)
abstract class BoxCarrier[R <: Animal](box: TransportBox[R]) {
def speed: Int
def talkToAnimal: Unit = println("The carrier says hello to "+box.animal.name)
}
// 3.
new BoxCarrier(aBox) {
def speed: Int = 12
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment