Skip to content

Instantly share code, notes, and snippets.

@takezoe
Created December 25, 2011 17:46
Show Gist options
  • Save takezoe/1519540 to your computer and use it in GitHub Desktop.
Save takezoe/1519540 to your computer and use it in GitHub Desktop.
Example of type class in Scala
/** 型クラス */
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
}
// 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))
@takezoe
Copy link
Author

takezoe commented Dec 25, 2011

実際にこんな用途に使うかどうかは置いておくとして。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment