implicit convertions [scala 2.10.0]

53 views
Skip to first unread message

eric vantillard

unread,
Feb 12, 2013, 12:13:40 PM2/12/13
to scala-l...@googlegroups.com
The question is :
can somebody explain me where I was wrong with my first solution ?

Details:
Today I tried to compile this code :

object Sample extends App{
import scala.language.implicitConversions
implicit def asOptional[T, U](value: U)(implicit fn: U => T): Option[T] = Some(fn(value))
case class A(v:Option[Double])
A(asOptional(1))
A(1)
}

and I have compilation error :
<console>:15: error: type mismatch;
 found   : Int(1)
 required: Option[Double]
              A(1)
on #scala irc room they found a solution (thank you all guys) : split it down like this :
// implicit def asOptional[T, U](value: U)(implicit fn: U => T): Option[T] = Some(fn(value))

implicit def asOptional[U,T](value: U)(implicit fn: U => T): Option[T] = fn(value)

implicit def toOption[T](value: T): Option[T] = Option(value)

can somebody explain me where I was wrong with my first solution ?
 

Paul Phillips

unread,
Feb 12, 2013, 1:56:06 PM2/12/13
to scala-l...@googlegroups.com

On Tue, Feb 12, 2013 at 9:13 AM, eric vantillard <eric.vantil...@gmail.com> wrote:
can somebody explain me where I was wrong with my first solution ?

To me it appears to be a bug, but I'm always wrong about these implicit situations.

The implicit search goes looking for Int => Option[Double] and never finds it. There is an implicit from U => Option[T] which can be called explicitly, but it appears to infer T=Int and U=Nothing. This is one of those things which strikes in a variety of places due to the order in which type parameters are solved.

By way of illustration, it compiles if you add this, which gives you an implicit with the specific types it needs to find.

  implicit val bippy = asOptional[Double, Int] _

Reply all
Reply to author
Forward
0 new messages