Scala: can the compiler efficiently optimize constants?

Consider the following:

object Foo {
  val BUFFER_SIZE = 1024
}

class Foo {
  .
  .
  .

  val buffer = new Array[Byte](Foo.BUFFER_SIZE)

This is too verbose and does not seem elegant compared to the Java static (final) variable, especially because the definition and use of the constant is too far apart to immediately understand the code. I want something like this:

class Foo {
  val BUFFER_SIZE = 1024

  val buffer = new Array[Byte](BUFFER_SIZE)

The question is, is the Scala compiler smart enough not to create a BUFFER_SIZE for each Foo instance to waste time and space? Or do you have to go first?

+4
source share
2 answers

TL; DR: No, this is not so good, but you can be guided by the compiler.

And it's easy to check (I entered the code in test.scala):

scalac test.scala 
javap Foo.class
// Compiled from "test.scala"
// public class Foo {
//   public int BUFFER_SIZE();
//   public byte[] buffer();
//   public Foo();
// }

, val , . -:

javap -c Foo.class
Compiled from "test.scala"
public class Foo {
  public int BUFFER_SIZE();
    Code:
       0: aload_0       
       1: getfield      #15                 // Field BUFFER_SIZE:I
       4: ireturn       

  // .... irrelevant parts

, getfield, , ( getstatic, ).

public final int BUFFER_SIZE();
    Code:
       0: sipush        1024
       3: ireturn 

, BUFFER_SIZE final:

class Foo {
  final val BUFFER_SIZE = 1024

  val buffer = new Array[Byte](BUFFER_SIZE)
}

private[this], @ghik, . , final , private[this] .

+6

, , (, Java).

, ( ), - ​​ private[this]:

class Foo {
  private[this] val BUFFER_SIZE = 1024
  val buffer = new Array[Byte](BUFFER_SIZE)
}

, , - .

+2

All Articles