Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j5ik2o/95004d1608f0f059ebb3 to your computer and use it in GitHub Desktop.
Save j5ik2o/95004d1608f0f059ebb3 to your computer and use it in GitHub Desktop.
// あらゆる型を加算できる型クラス Adder
trait Adder[A] {
def add(a: A, b: A): A
}
// 型クラスのインスタンス Int用
implicit val intAdder = new Adder[Int] {
override def add(a: Int, b: Int): Int = a + b
}
// 型クラスのインスタンス String用
implicit val stringAdder = new Adder[String] {
override def add(a: String, b: String): String = s"$a+$b"
}
object Main extends App {
def add[A](a: A, b: A)(implicit adder: Adder[A]): A = adder.add(a, b)
println(add(1, 2)) // 3
println(add("a","b")) // a+b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment