Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Last active August 29, 2015 14:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shinpeim/76c687b3c9a8f8126da0 to your computer and use it in GitHub Desktop.
Save Shinpeim/76c687b3c9a8f8126da0 to your computer and use it in GitHub Desktop.
// 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