logo       

Re: Implicit type conversion: msg#00503

lang.scala

Subject: Re: Implicit type conversion

Tony,

You can do without transitivity. Example:

  implicit def AtoB(x: A): B = ...
  implicit def BtoC(x: B): C = ...

In that case you cannot convert from A to C. However, you can
plan ahead, by writing:
 
  implicit def AtoB(x: A): B = ...
  implicit def BtoC[B1](x: B1)(implicit toB: B1 => B): C = ...

or, equivalently, by giving BtoC a view-bound:

  implicit def BtoC[B1 <% B](x: B1): C = ...

Then A can be converted to C. The conversion that is implicitly inserted is

    a: A => BtoC(a)(AtoB)

Cheers

 -- Martin

On 1/29/07, Tony Morris <tmorris@xxxxxxxxxxx > wrote:
Jon Pretty wrote:
> Hi Tony,
>
> Tony Morris wrote:
>> I have found what appears to be an anomaly in implicit type coercion. I
>> have attempted to trivialise my example, but it is still 50 or so LOC. I
>> have annotated the code with the relevant question in the relevant place
>> in the code with comments. The problem is that this code will not
>> compile.
>
> Note that implicit defs (which were called 'views' prior to Scala 2) are
> not applied transitively. If the compiler finds a function call with no
> matching definition, it will then check to see if, by applying any of
> the exact implicit defs within scope to any of the parameters, it can
> find a matching function definition.  If it can't, then it complains.  I
> believe it complains in the event of any ambiguity with overloaded
> definitions or multiple 'useful' implicit defs within scope.
>
> Implicit definitions should be used with care.  Having many implicit
> definitions within scope can be confusing, and it was a conscious design
> decision to disallow transitivity.
>
> Cheers,
> Jon
>
>

OK, so that explains why one compiles and the other doesn't. Though,
I'll express my disappointment at the lack of transitivity.

Thanks.

Tony Morris
http://tmorris.net/




<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise