Created
November 16, 2011 15:34
-
-
Save dt/1370365 to your computer and use it in GitHub Desktop.
musing on setFromAny
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
// goal: define one method which can be given arguments of different types (i.e. without a common supertype) | |
// lift (diaf) uses setFromAny(arg: Any) and a match, but in doing so loses typesafety. | |
case class Foo(i: Int) | |
case class Bar(v: String) | |
case class Baz(d: Boolean) | |
val foo = Foo(1) | |
val bar = Bar("1") | |
val baz = Baz(false) | |
case class QuxArgument[T](value: T) | |
implicit def fooToQuxArg(x: Foo): QuxArgument[Foo] = QuxArgument(x) | |
implicit def barToQuxArg(x: Bar): QuxArgument[Bar] = QuxArgument(x) | |
def qux[T](v: QuxArgument[T]) = v.value match { | |
case Foo(x) => println("foo "+x) | |
case Bar(x) => println("bar "+x) | |
case i => println("wtf "+i) | |
} | |
scala> qux(foo) | |
foo: 1 | |
scala> qux(bar) | |
bar: 1 | |
scala> qux(baz) | |
<console>:38: error: type mismatch; | |
found : Baz | |
required: QuxArgument[?] | |
qux(baz) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment