Scala seems to apply the implicit class conversion on the largest possible expression, as in the following example:
scala> class B { def b = { println("bb"); true } }
defined class B
scala> class A { def a = { println("aa"); new B } }
defined class A
scala> (new A).a.b
aa
bb
res16: Boolean = true
scala> class XXX(b: => Boolean) { def xxx = 42 }
defined class XXX
scala> implicit def toXXX(b: => Boolean) = new XXX(b)
toXXX: (b: => Boolean)XXX
scala> (new A).a.b.xxx
res18: Int = 42
I’m very happy about this fact, but my question is that which part of the SLS specifies this behavior? Why does it not evaluate (new A).a.b to true first for example, and just apply the conversion on that value?
As answered by Ryan Hendrickson on the mailing list:
[The definition] you’re looking for is in Section 7.3, in the list of the three situations in which views are applied:
of T. In this case, a view v is searched which is applicable to e and whose result
contains a member named m. The search proceeds as in the case of implicit
parameters, where the implicit scope is the one of T. If such a view is found,
the selection e.m is converted to v(e).m.
So the compiler can only generate something that is semantically equivalent to v(e).m, and as you’ve demonstrated, when by-name parameters are involved
is not semantically equivalent to
v(e).m.