Scala scope implicit class conversion

Scala seems to apply the implicit class transform in the highest 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 am very pleased with this fact, but my question is, what part of the SLS defines this behavior? Why does he, for example, not evaluate (new A).a.bto trueand simply apply the transformation to this value?

+3
source share
2 answers

As Ryan Hendrickson replied on the mailing list:

The [definition] you are looking for is given in section 7.3, in a list of three situations in which views are applied:

  • e.m e T, T. v, ​​ e m. , , - T. , e.m v (e).m.

, , v (e).m, , , -

val x = e
v(x).m

v(e).m.

0

,

(new A).a.b.xxx

(.. )

toXXX((new A).a.b).xxx

, -Xprint:typer Scala.

private[this] val res3: Int = $line5.$read.$iw.$iw.toXXX(new $line2.$read.$iw.$iw.A().a.b).xxx;

, , Scala (new A).a.b true . , , , , toXXX((new A).a.b).xxx.

0

All Articles