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.

0

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.