Scala - creating objects without making the constructor parameter a member of the object

I have

class Address(elem: scala.xml.Elem){
    val attr1 = (elem \ "attr1") text
    ...
}

I do not want elem to be a member of Address in order to maintain a minimal footprint, as I create several million such objects in memory. What is the way scala achieve this? Thank.

+3
source share
1 answer

You achieve it exactly as you showed. Just make sure that you only refer to elemas part of the class initializer, and not to other methods where it will need to be stored so that it can be called.

Here's the bytecode for what you wrote (use javap -p ClassNameon compiled classes):

public Address(scala.xml.Elem);
  Code:
   0:   aload_0
   1:   invokespecial   #18; //Method java/lang/Object."<init>":()V
   4:   aload_0
   5:   aload_1
   6:   ldc #19; //String attr1
   8:   invokevirtual   #25; //Method scala/xml/Elem.$bslash:(Ljava/lang/String;)Lscala/xml/NodeSeq;
   11:  invokevirtual   #30; //Method scala/xml/NodeSeq.text:()Ljava/lang/String;
   14:  putfield    #11; //Field attr1:Ljava/lang/String;
   17:  return

, putfield, , val attr1. elem , putfield. val a def, :

public Address(scala.xml.Elem);
  Code:
   0:   aload_0
   1:   aload_1
   2:   putfield    #12; //Field elem:Lscala/xml/Elem;
   5:   aload_0
   6:   invokespecial   #31; //Method java/lang/Object."<init>":()V
   9:   return

, elem , def .

, elem ,

class Address(val elem: scala.xml.Elem) { ... }

( val).

case, : case , , , , .

+11

Source: https://habr.com/ru/post/1767642/


All Articles