Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_40).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
// Nameable is now a typeclass, not an interface
trait Nameable[P] {
def getName(p: P): String
}
case class Person(name: String)
case class Dog(name: String)
case class Building(floors: Int)
// provide instances of the Nameable typeclass for Person, Dog, anything else you're interested in naming.
implicit val nameablePerson = new Nameable[Person] {
def getName(p: Person) = p.name
}
implicit val nameableDog = new Nameable[Dog] {
def getName(d: Dog) = d.name
}
// you can also provide a fallback instance of the typeclass for any other type
// (the implicit vals above will take precedence over this for Person and Dog)
implicit def nameableAnythingElse[A] = new Nameable[A] {
def getName(a: A) = a.toString
}
def doSomething[A](a: A)(implicit ev: Nameable[A]): String = {
s"the thing's name is ${ev.getName(a)}"
}
// Exiting paste mode, now interpreting.
defined trait Nameable
defined class Person
defined class Dog
defined class Building
nameablePerson: Nameable[Person] = $anon$1@247310d0
nameableDog: Nameable[Dog] = $anon$2@1033576a
nameableAnythingElse: [A]=> Nameable[A]
doSomething: [A](a: A)(implicit ev: Nameable[A])String
scala> val chris = Person("chris")
chris: Person = Person(chris)
scala> doSomething(chris)
res0: String = the thing's name is chris
scala> val building = Building(floors = 10)
building: Building = Building(10)
scala> doSomething(building)
res1: String = the thing's name is Building(10)
// Nameable is now a typeclass, not an interface
trait Nameable[P] {
def getName(p: P): String
}
case class Person(name: String)
case class Dog(name: String)
case class Building(floors: Int)
// provide instances of the Nameable typeclass for Person, Dog, anything else you're interested in naming.
implicit val nameablePerson = new Nameable[Person] {
def getName(p: Person) = p.name
}
implicit val nameableDog = new Nameable[Dog] {
def getName(d: Dog) = d.name
}
// you can also provide a fallback instance of the typeclass for any other type
// (the implicit vals above will take precedence over this for Person and Dog)
implicit def nameableAnythingElse[A] = new Nameable[A] {
def getName(a: A) = a.toString
}
def doSomething[A](a: A)(implicit ev: Nameable[A]): String = {
s"the thing's name is ${ev.getName(a)}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment