« Return to Thread: [scala] Why is this a diverging implicit?

Re: [scala] Why is this a diverging implicit?

by Henry Ware-2 :: Rate this Message:

Reply to Author | View in Thread

I don't ken the implicits system either, so I can't explain much.

But, depending on what you are trying to do, this might help.

 trait Giver[T] { def give: T  }

 implicit def IntGiver(i:Int)=new Giver[Int] { def give = 3 }

 def getGiver[T <% Giver[T]]:Giver[T] = null.asInstanceOf[T];
 def giveMeA[T <% Giver[T]]:T = getGiver[T].give;
 def main(a:Array[String])={
   Console.println("I have an int: " + giveMeA[Int])
  }

-Henry Ware

On Thu, Jul 17, 2008 at 9:07 AM, Aaron Harnly <scala@...> wrote:

> I'm puzzled as to why the following short example yields a "diverging implicit
> expansion" error. I placed the AnyVal bound on the type parameter T
> specifically to prevent the compiler from worrying that it could generate
> Giver[Giver[Int]], Giver[Giver[Giver[Int]]], etc.
>
> Can someone who kens the implicits system better than I explain what goes awry
> here? much thanks, ~aaron
>
> trait Giver[T <: AnyVal] { def give: T  }
> implicit def fromGiver[T <: AnyVal](implicit giver: Giver[T]): T = giver.give
>
> implicit object IntGiver extends Giver[Int] { def give = 3 }
>
> def anImplicit[T](implicit t: T) = t
> Console.println("I have an int: " + anImplicit[Int])
>
> /**
> The above yields this error:
> [08:32 AM aaron@macbookpro: implicits] scala giver.scala
>
> (fragment of giver.scala):7: error: diverging implicit expansion for type Int
> starting with method fromGiver
> Console.println("I have an int: " + anImplicit[Int])
>                                    ^
> one error found
> !!!
> discarding <script preamble>
>
> */
>
>

 « Return to Thread: [scala] Why is this a diverging implicit?

LightInTheBox - Buy quality products at wholesale price!