3

Recently, I looked at the example of implicit chain, implicit def foo[C3 <% C](c: C). I think I am confused about the difference between <% and (implicit c : C).

If I write implicit def bToC[C3 <: C](c: C)(implicit c3 : C3), it gives a compilation error, but why is that, implicit def should be in the scope?

Edit:

Can someone explain why

implicit def aToB[A1 : A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n)

and

implicit def aToB[A1 <: A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n)

are not working ?

Many thanks in advance

Community
  • 1
  • 1
Xiaohe Dong
  • 4,953
  • 6
  • 24
  • 53
  • 1
    It is called "view bound" - http://stackoverflow.com/questions/4465948/what-are-scala-context-and-view-bounds –  Jul 28 '14 at 16:18

1 Answers1

1

[C3 <% C] means implicit ev: C3 => C. In other word, an implicit function that converts C3 to C. So all C3 objects in the scope can be C objects.

def intPlus1[A <% Int](a: A) = a + 1
// def intPlus1[A](a: A)(implicit ev: A => Int) = a + 1

implicit def string2int(s: String) = s.toInt // String => Int

intPlus1("100")
intPlus1("100")(string2int)
// the result bark bark

Note that A <% A for any A, because an implicit function A => A is Predef'ed, thus B <% A if B <: A too, as @rightfold mentions in the comment. :)

Ryoichiro Oka
  • 1,949
  • 2
  • 13
  • 20
  • Note that this includes subtyping relationships, so α <: β → α <% β. –  Jul 28 '14 at 17:31
  • but why implicit def aToB[A1 : A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n) and implicit def aToB[A1 <: A](a: A1)(implicit ev: Int => A1): B = new B(a.n, a.n) are not working ? – Xiaohe Dong Jul 29 '14 at 00:43
  • @Cloudtech There's no way I can answer to the question while the definition of `A`, `A1` and `B` is not provided :P – Ryoichiro Oka Jul 29 '14 at 02:09