ULong#apply's @inline

6 views
Skip to first unread message

Kevin Meredith

unread,
Apr 28, 2015, 12:31:52 PM4/28/15
to spire...@googlegroups.com
Looking at the ULong object's apply method:

object ULong extends ULongInstances {
  @inline final def apply(n: Long): ULong = new ULong(n)

Why is this annotation used?

Note - I know nothing about inline-ing other than reading these 2 stackoverflow posts: 


Thanks

Erik Osheim

unread,
Apr 28, 2015, 12:49:41 PM4/28/15
to Kevin Meredith, spire...@googlegroups.com
Hi Kevin,

On Tue, Apr 28, 2015 at 09:31:52AM -0700, Kevin Meredith wrote:
> object ULong extends ULongInstances {
> @inline final def apply(n: Long): ULong = new ULong(n)
>
> Why is this annotation used?

It's just an optimization. The details are in how value classes
work. At runtime, ULong will mostly just be treated as a Long, but in
certain cases (e.g. comparisons, division) different code will be
used from what would happen with Long.

Since ULong is a value class, the code:

val x = new ULong(33L)

will usually be rewritten to something similar to:

val x = 33L

This is great, but in Scala it is often nice to provide factory
constructors rather than relying on new. So we could define:

object ULong {
def apply(n: Long): ULong = new ULong(n)
}

which in many cases will be equivalent to:

def apply(n: Long): Long = n

However, this means that:

val x = ULong(33L)

will be rewritten to:

val x = ULong.apply(33L)

Which is not ideal, since apply(33L) just returns 33L.

Using @inline and final, we can ensure that ULong(...) behaves the
same as new ULong(...).

Hope this helps.

-- Erik
Reply all
Reply to author
Forward
0 new messages