Skip to content

private[this] var field doesn't get updated in constructor body #12003

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Jasper-M opened this issue May 15, 2020 · 4 comments
Closed

private[this] var field doesn't get updated in constructor body #12003

Jasper-M opened this issue May 15, 2020 · 4 comments
Assignees
Milestone

Comments

@Jasper-M
Copy link

Jasper-M commented May 15, 2020

reproduction steps

using Scala 2.12.11,

scala> class Foo(private[this] var a: Int) {
     |   a = a + 1
     |   def foo = a
     | }
defined class Foo

scala> new Foo(0).foo
res0: Int = 0

problem

I mutate a in the constructor body, so I would expect the field to be mutated, not just the constructor parameter as you can see here in the bytecode (iload_1 and istore_1 instead of getfield and putfield):

scala> :javap -c -filter Foo
Compiled from "<console>"
public class Foo {
  public int foo();
    Code:
       0: aload_0
       1: getfield      #19                 // Field a:I
       4: ireturn

  public Foo(int);
    Code:
       0: aload_0
       1: iload_1
       2: putfield      #19                 // Field a:I
       5: aload_0
       6: invokespecial #26                 // Method java/lang/Object."<init>":()V
       9: iload_1
      10: iconst_1
      11: iadd
      12: istore_1
      13: return
}

This is "fixed" in Scala 2.13 but it has other issues (#12002).

The rule should be, if a field needs to be created always use the field. Otherwise always use the local parameter.

@Jasper-M Jasper-M changed the title private[this] constructor var doesn't get updated private[this] var field doesn't get updated in constructor body May 15, 2020
@SethTisue SethTisue added this to the 2.12.12 milestone May 15, 2020
@SethTisue
Copy link
Member

SethTisue commented May 15, 2020

Normally we'd close the ticket since it doesn't occur in 2.13 (and there is a separate ticket for the related problem in 2.13), but in this case I'm keeping it open and tentatively milestoning it 2.12.12 so we remember to at least consider if the (eventual) fix for #12002 is backport-able and might fix this too.

@som-snytt
Copy link

#6880

@Jasper-M
Copy link
Author

I'm sorry about the "fixed" thing 😅

@som-snytt
Copy link

One mole at a time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants