Last active
December 5, 2018 15:44
-
-
Save Shinpeim/7763591 to your computer and use it in GitHub Desktop.
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
| object Main extends App { | |
| trait IntOrString{ | |
| val value:Any // ここつらい | |
| } | |
| implicit class MyInt(self: Int) extends IntOrString{ | |
| val value:Int = self | |
| } | |
| implicit class MyString(self:String) extends IntOrString{ | |
| val value:String = self | |
| } | |
| // implicit conversion が効くので ListにInt とString を放り込める | |
| val list: List[IntOrString] = List(1, "nyan") | |
| println(list) // => List(Main$MyInt@7c987c42, Main$MyString@7f0610f5) | |
| // という感じでMyInt,MyString型になってしまう(あたりまえ) | |
| println(list.map(_.value)) | |
| //こうすればInt, Stringでとれるけどうーん…… | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment