This page is no longer maintained — Please continue to the home page at www.scala-lang.org

What's wrong with implicits here?

2 replies
ojow
Joined: 2009-10-21,
User offline. Last seen 37 weeks 3 days ago.

Hello, while trying to implement a type safe authorization mockup,
i've encountered a problem with implicits.
The simplified code looks like this: http://pastie.org/1005282
What's wrong and how do i solve it?
I guess it might have been discussed, but i can't find anything.

Daniel Degrandi
Joined: 2010-05-10,
User offline. Last seen 42 years 45 weeks ago.
Re: What's wrong with implicits here?

Oleg Galako schrieb:
> Hello, while trying to implement a type safe authorization mockup,
> i've encountered a problem with implicits.
> The simplified code looks like this: http://pastie.org/1005282
> What's wrong and how do i solve it?
> I guess it might have been discussed, but i can't find anything.
>

This works:

object Test {
trait A
trait B

trait Builder[From, To] {
def buildFrom(x: From): To
}

implicit val a2bBuilder = new Builder[A, B] {
override def buildFrom(x: A) = new B{}
}

implicit def a2b[From<:A, To>:B](x: From)(implicit bl: Builder[From,
To]): To = bl.buildFrom(x)

def f(b: B) = println(b)

def main(args: Array[String]) {
val a: A = new A{}
f(a)
}
}

The compiler must get a clue which implicit conversion is useful, so you
need the type constraints.

Dan

Daniel Degrandi
Joined: 2010-05-10,
User offline. Last seen 42 years 45 weeks ago.
Re: What's wrong with implicits here?

Daniel Degrandi schrieb:
>
>
> Oleg Galako schrieb:
>> Hello, while trying to implement a type safe authorization mockup,
>> i've encountered a problem with implicits.
>> The simplified code looks like this: http://pastie.org/1005282
>> What's wrong and how do i solve it?
>> I guess it might have been discussed, but i can't find anything.
>>
>
> This works:
>
> object Test {
> trait A
> trait B
>
> trait Builder[From, To] {
> def buildFrom(x: From): To
> }
>
> implicit val a2bBuilder = new Builder[A, B] {
> override def buildFrom(x: A) = new B{}
> }
>
> implicit def a2b[From<:A, To>:B](x: From)(implicit bl: Builder[From,
> To]): To = bl.buildFrom(x)
>
> def f(b: B) = println(b)
>
> def main(args: Array[String]) {
> val a: A = new A{}
> f(a)
> }
> }
>
> The compiler must get a clue which implicit conversion is useful, so
> you need the type constraints.
>
> Dan
Actually, the lower bound of the target type appears to be sufficient:

implicit def a2b[From, To>:B](x: From)(implicit bl: Builder[From, To]):
To = bl.buildFrom(x)

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland