4

Consider:

class Wrap(val amount :Int) extends AnyVal

object Wrap {
    @inline final def apply(int :Int) = new Wrap(int)
}

object Playground {
    val w = Wrap(1)
}      

compiling with (2.11.7) scalac -feature -Xprint:all Playground.scala I see

Playground.this.w = Wrap.apply(1);

and indeed, javap -v -private Playground shows:

    89: invokevirtual #75                 // Method Wrap$.apply:(I)I
    92: putfield      #33                 // Field w:I

When changing Playground constructor to:

val w = new Wrap(1)

both show assignment of literal 1 to w as expected. I am frankly quite dissapointed with this discovery, as it practically prevents type-level programming using value classes (where an ephemeric value class instance is created by a chain of trivial inlined methods.

Turin
  • 2,208
  • 15
  • 23

0 Answers0