score:8

Accepted answer

anyval subclasses are stack allocated, where possible. the exception happens with newer user-created classes that extend anyval on 2.10.0, if the object escapes the scope.

any and anyval will be stored on the heap... unless you @specialized.

score:3

i'm also new to scala, but afaik, a scala variable can not contain an actual object. it can at most contain a reference to an object. (you get a reference from new and there's no dereference operator to follow that reference to an object (such as * in c++ for instance).)

in other words, all non-primitive values live on the heap. (just as in java.)

score:3

the jvm does not support reification of generics and provides no means of having a primitive super type for all primitive types. thus a field or parameter of type anyval will always be of type java.lang.object in the byte code and boxing/unboxing will be performed.

this does not necessarily mean that the value is stored on the heap though as the jvm may perform certain optimizations. you have to still expect a runtime penalty though.

score:14

a.scala:

class a {
  val a: anyval = 1
  val b: int = 1
}

scalac a.scala

javap -c a

public class a extends java.lang.object implements scala.scalaobject{
 public java.lang.object a();
  code:
   0:   aload_0
   1:   getfield        #13; //field a:ljava/lang/object;
   4:   areturn

 public int b();
  code:
   0:   aload_0
   1:   getfield        #16; //field b:i
   4:   ireturn

 public a();
  code:
   0:   aload_0
   1:   invokespecial   #22; //method java/lang/object."<init>":()v
   4:   aload_0
   5:   iconst_1
   6:   invokestatic    #28; //method scala/runtime/boxesruntime.boxtointeger:(i)ljava/lang/integer;
   9:   putfield        #13; //field a:ljava/lang/object;
   12:  aload_0
   13:  iconst_1
   14:  putfield        #16; //field b:i
   17:  return
}

so explicit anyval usage leads to boxed primitive on the heap, as expected.


Related Query

More Query from same tag