Skip to content

Different behavior of val and final val in objects #18698

Closed as not planned
Closed as not planned
@JD557

Description

@JD557

Compiler version

3.3.1

Minimized code

object Normal:
  val x = 5

object Final:
  final val x = 5

Output

public final class finalval$_$Normal$ implements java.io.Serializable {
  private final int x;

  public finalval$_$Normal$();
    Code:
       0: aload_0
       1: invokespecial #16                 // Method java/lang/Object."<init>":()V
       4: aload_0
       5: iconst_5
       6: putfield      #18                 // Field x:I
       9: return

  public int x();
    Code:
       0: aload_0
       1: getfield      #18                 // Field x:I
       4: ireturn
}

public final class finalval$_$Final$ implements java.io.Serializable {
  public finalval$_$Final$();
    Code:
       0: aload_0
       1: invokespecial #14                 // Method java/lang/Object."<init>":()V
       4: return

  public final int x();
    Code:
       0: iconst_5
       1: ireturn
}

Expectation

Since the generated classes for objects are final, I would expect that all vals declared in an object would be treated as final as well (including in this case, using iconst).

See VirtusLab/scala-cli#2462 for an example where this difference lead to huge performance differences on Java 8 and 11.

Notes

Like #17519, I'm not sure if changing this would trigger MiMA warnings, but since the class is already final I don't think there's any way for this to trigger binary compatibility problems.

I'm basing my expectations on this Stack Overflow question/answer: Non-final methods in a final class

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions