Java – how to allocate memory in Scala
We know that, unlike Java, Scala treats everything as an object
For example, we have –
object A{ val arg1=1 def myFun(arg2:Int)=arg1 } class A{ val arg1=1 def myFun(arg2:Int)=arg1 } trait A{ val arg1=1 def myFun(arg2:Int)=arg1 }
>Now, since everything in scala is an object, how will memory allocation happen? > Will everything get memory in the heap except reference variables? > When creating a class instance in Java, the methods and variables in the class will get the memory in the heap How does singleton objects happen here? > If everything is in the heap, will it affect performance? > Like Java, memory is divided into five parts, namely heap, stack, methodarea, etc How does memory allocation work in scala?
Solution
Scala runs on the JVM and is based on Java libraries
Scala files (*. Scala) will be compiled into Java class bytecode and run on the JVM For your example:
object A{ val arg1=1 def myFun(arg2:Int)=arg1 }
Will be translated into (bytecode decompiled by javap):
public class A$extends java.lang.Object{ public static final A$MODULE$; private final int arg1; public static {}; public int arg1(); public int myFun(int); public A$(); }
class A{ val arg1=1 def myFun(arg2:Int)=arg1 }
Will be translated into (bytecode decompiled by javap):
public class A extends java.lang.Object{ private final int arg1; public int arg1(); public int myFun(int); public A(); }
trait A{ val arg1=1 def myFun(arg2:Int)=arg1 }
Will be translated into (bytecode decompiled by javap):
public interface A{ public abstract void $line5$$read$A$_setter_$arg1_$eq(int); public abstract int arg1(); public abstract int myFun(int); }
So for your other memory problems, I think it is the same as Java