Skip to content

Instantly share code, notes, and snippets.

@akirillov
Last active October 20, 2015 17:57
Show Gist options
  • Save akirillov/94101a5566c2a4aad74f to your computer and use it in GitHub Desktop.
Save akirillov/94101a5566c2a4aad74f to your computer and use it in GitHub Desktop.
Simple example of ad-hoc polymorphism in Scala
//single parameter function for different types
trait Size[A] {
def size(a: A): Int
}
def size[A: Size](a: A): Int = implicitly[Size[A]].size(a)
implicit object StringSize extends Size[String]{
override def size(a: String): Int = a.length
}
size("test")
//res0: Int = 4
implicit object ListSize extends Size[List]{
override def size(a: List): Int = a.size
}
size(List(1,2,3))
//res1: Int = 3
//custom sum behavior for two parameters
trait Plus[A] {
def plus(a1: A, a2: A): A
}
def plus[A: Plus](a1: A, a2: A): A = implicitly[Plus[A]].plus(a1, a2)
implicit object PlusInt extends Plus[Int]{
override def plus(a1: Int, a2: Int): Int = a1 + a2
}
plus(5, 6)
//res2: Int = 11
implicit object PlusString extends Plus[String]{
override def plus(a1: String, a2: String): String = a1.concat(a2)
}
plus("test", "string")
//res3: String = teststring
case class Person(age: Int)
implicit object PlusPerson extends Plus[Person]{
override def plus(a1: Person, a2: Person): Person = Person(a1.age + a2.age)
}
plus(Person(13), Person(14))
//res4: Person = Person(27)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment