Created
September 29, 2014 08:56
-
-
Save y-yoshinoya/42eeadd04e7b5e8acb9d to your computer and use it in GitHub Desktop.
bundling implicit conversions
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
class Rich[S] { | |
def conversion(s: S) = new Foo {} | |
def optionConversion(s: Option[S]) = new Foo {} | |
} | |
trait Foo { | |
def foo = "foo" | |
} | |
object Foo { | |
implicit def toFoo[S](s: S)(implicit rich: Rich[S]) = rich.conversion(s) | |
implicit def toFoo[S](s: Option[S])(implicit rich: Rich[S]) = rich.optionConversion(s) | |
} | |
object Main extends App { | |
import Foo._ | |
implicit val richString = new Rich[String] { | |
override def conversion(s: String) = new Foo { override def foo = "aaa" } | |
override def optionConversion(s: Option[String]) = new Foo { override def foo = "bbb" } | |
} | |
implicit val richInt = new Rich[Int] | |
println("sss".foo) | |
println(Option("sss").foo) | |
println(1.foo) | |
println(Option(1).foo) | |
} |
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
trait Foo { | |
def foo = "foo" | |
} | |
object Main extends App { | |
class RichString(s: String) extends Foo { | |
override def foo = "aaa" | |
} | |
class RichOptionString(s: Option[String]) extends Foo { | |
override def foo = "bbb" | |
} | |
class RichInt(n: Int) extends Foo | |
class RichOptionInt(n: Option[Int]) extends Foo | |
implicit def toRichString(str: String) = new RichString(str) | |
implicit def toRichOptionString(str: Option[String]) = new RichOptionString(str) | |
implicit def toRichInt(n: Int) = new RichInt(n) | |
implicit def toRichOptionInt(n: Option[Int]) = new RichOptionInt(n) | |
println("sss".foo) | |
println(Option("sss").foo) | |
println(1.foo) | |
println(Option(1).foo) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Implicit macro を使えば汎用的な暗黙変換を事前に定義できることがわかったのでこれは不要になる