Last active
August 29, 2015 14:06
-
-
Save j5ik2o/95004d1608f0f059ebb3 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
// あらゆる型を加算できる型クラス 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