Last active
August 29, 2015 14:03
-
-
Save Shinpeim/76c687b3c9a8f8126da0 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
// 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)) |
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
// 型クラスを使うとコンパイル時に解決されるので | |
// 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