Skip to content

Instantly share code, notes, and snippets.

@y-yoshinoya
Created September 29, 2014 08:56
Show Gist options
  • Save y-yoshinoya/42eeadd04e7b5e8acb9d to your computer and use it in GitHub Desktop.
Save y-yoshinoya/42eeadd04e7b5e8acb9d to your computer and use it in GitHub Desktop.
bundling implicit conversions
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)
}
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)
}
@y-yoshinoya
Copy link
Author

Implicit macro を使えば汎用的な暗黙変換を事前に定義できることがわかったのでこれは不要になる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment