Create a gist now

Instantly share code, notes, and snippets.

// type erasure のせいでメソッドのオーバーロードができない
// 以下のようなコンパイルエラーになる
//
// error: double definition:
// method nyan:(x: Option[Boolean])Int and
// method nyan:(x: Option[Int])Int at line 2
// have same type after erasure: (x: Option)Int
def nyan(x: Option[Int]) = 0
def nyan(x: Option[Boolean]) = 1
val intOption: Option[Int] = Some(1)
val boolOption: Option[Boolean] = None
println(nyan(intOption))
println(nyan(boolOption))
// 型クラスを使うとコンパイル時に解決されるので
// type erasure関係なくアドホック多相できる
trait Nyan[T] {
def doNyan(x:T):Int
}
implicit object IntNyan extends Nyan[Option[Int]] {
def doNyan(x:Option[Int]):Int = 0
}
implicit object BooleanNyan extends Nyan[Option[Boolean]] {
def doNyan(x:Option[Boolean]):Int = 1
}
def nyan[T](x: T)(implicit instance: Nyan[T]) = instance.doNyan(x)
val intOption:Option[Int] = Some(1)
val boolOption:Option[Boolean] = None
println(nyan(intOption)) // => 0
println(nyan(boolOption)) // => 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment