Note that there are some explanatory texts on larger screens.

plurals
  1. POScala: Making implicit conversion A->B work for Option[A] -> Option[B]
    primarykey
    data
    text
    <p>I'm trying to write a function which re-uses the implicit conversions which I have for Object A -> Object B when they are wrapped in an Option in a generic way so that Option[A] -> Option[B] conversions also work.</p> <p>What I've come up with is:</p> <pre><code>implicit def fromOptionToOption[A, B](from: Option[A])(implicit conversion: (A) =&gt; B): Option[B] = from.map(conversion(_)) </code></pre> <p>This works when I assign a Some(..) to a value but not when I assign an Option val; see the following console output:</p> <pre><code>scala&gt; trait T defined trait T scala&gt; case class Foo(i: Int) extends T defined class Foo scala&gt; case class Bar(i: Int) extends T defined class Bar scala&gt; implicit def fromFooToBar(f: Foo):Bar = Bar(f.i) fromFooToBar: (f: Foo)Bar scala&gt; implicit def fromBarToFoo(b: Bar):Foo = Foo(b.i) fromBarToFoo: (b: Bar)Foo scala&gt; implicit def fromOptionToOption[A, B](from: Option[A])(implicit conversion: (A) =&gt; B): Option[B] = from.map(conversion(_)) fromOptionToOption: [A, B](from: Option[A])(implicit conversion: (A) =&gt; B)Option[B] scala&gt; val foo: Option[Foo] = Some(Bar(1)) foo: Option[Foo] = Some(Foo(1)) // THIS WORKS as expected scala&gt; val fooOpt = Some(Foo(4)) fooOpt: Some[Foo] = Some(Foo(4)) scala&gt; val barOpt2: Option[Bar] = fooOpt &lt;console&gt;:16: error: type mismatch; found : Some[Foo] required: Option[Bar] val barOpt2: Option[Bar] = fooOpt ^ //THIS FAILS. </code></pre> <p>I don't really see the difference between the first and second conversion. Somehow it doesn't invoke the implicit conversion in the latter. I guess it has something to do with the type system, but I can't see how just yet. Any ideas? -Albert (I'm on scala 2.9.1)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload