Created
December 25, 2011 17:46
-
-
Save takezoe/1519540 to your computer and use it in GitHub Desktop.
Example of type class in Scala
This file contains hidden or 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
/** 型クラス */ | |
trait Equals[A] { | |
def equals(a1: A, a2: A): Boolean | |
} | |
/** 型クラスを使用した関数(実際はcontext boundで書くかも?) */ | |
def equals[A](a1: A, a2: A)(implicit eq: Equals[A]): Boolean = eq.equals(a1, a2) | |
/** String用のEquals実装 */ | |
implicit object StrEquals extends Equals[String]{ | |
def equals(s1: String, s2: String): Boolean = s1.equals(s2) | |
} | |
/** Int用のEquals実装 */ | |
implicit object IntEquals extends Equals[Int]{ | |
def equals(i1: Int, i2: Int): Boolean = i1 == i2 | |
} | |
equals("a", "a") // => true | |
equals(1, 1) // => true | |
equals("1", 1) // コンパイルエラー | |
equals(true, false) // コンパイルエラー | |
// ちなみにimplicit objectじゃなくてimplicit defでやるとこんな感じ | |
/** String用のEquals実装を返すメソッド */ | |
implicit def strEquals = new Equals[String]{ | |
def equals(s1: String, s2: String): Boolean = s1.equals(s2) | |
} | |
/** Int用のEquals実装を返すメソッド */ | |
implicit def intEquals = new Equals[Int]{ | |
def equals(i1: Int, i2: Int): Boolean = i1 == i2 | |
} |
This file contains hidden or 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
// implicit defだと型パラメータが使えるのでこんな感じにできる? | |
/** 型クラス */ | |
trait Formatter[A] { | |
def format(value: A): String | |
} | |
/** 型クラスを使用した関数 */ | |
def println[A](value: A)(implicit f: Formatter[A]): Unit = Predef.println(f.format(value)) | |
/** すべてにマッチ */ | |
implicit def anyFormatter[A] = new Formatter[A]{ | |
def format(value: A): String = value.toString | |
} | |
/** java.util.Dateもしくはそのサブクラスにマッチ */ | |
implicit def dateFormatter[A <: java.util.Date] = new Formatter[A]{ | |
def format(value: A): String = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(value) | |
} | |
println("Hello World!") | |
println(9999) | |
println(new java.util.Date()) | |
println(new java.sql.Date(new java.util.Date().getTime)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
実際にこんな用途に使うかどうかは置いておくとして。