Created
June 12, 2013 17:49
-
-
Save twolfe18/5767545 to your computer and use it in GitHub Desktop.
private[this] vs private in scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Foo.scala | |
class Foo { | |
private var i = 0 | |
private[this] var j = 0 | |
def getJ = j | |
def iThing = i * i | |
def jThing = j * j | |
} | |
object Foo { | |
def main(args: Array[String]) { | |
val f = new Foo | |
f.i | |
f.getJ | |
f.iThing | |
f.jThing | |
} | |
} | |
// scalac Foo.scala && javap -c Foo$class | |
Compiled from "Foo.scala" | |
public class Foo { | |
public static void main(java.lang.String[]); | |
Code: | |
0: getstatic #16 // Field Foo$.MODULE$:LFoo$; | |
3: aload_0 | |
4: invokevirtual #18 // Method Foo$.main:([Ljava/lang/String;)V | |
7: return | |
public int Foo$$i(); | |
Code: | |
0: aload_0 | |
1: getfield #24 // Field Foo$$i:I | |
4: ireturn | |
public int getJ(); | |
Code: | |
0: aload_0 | |
1: getfield #32 // Field j:I | |
4: ireturn | |
public int iThing(); | |
Code: | |
0: aload_0 | |
1: invokevirtual #35 // Method Foo$$i:()I | |
4: aload_0 | |
5: invokevirtual #35 // Method Foo$$i:()I | |
8: imul | |
9: ireturn | |
public int jThing(); | |
Code: | |
0: aload_0 | |
1: getfield #32 // Field j:I | |
4: aload_0 | |
5: getfield #32 // Field j:I | |
8: imul | |
9: ireturn | |
public Foo(); | |
Code: | |
0: aload_0 | |
1: invokespecial #40 // Method java/lang/Object."<init>":()V | |
4: aload_0 | |
5: iconst_0 | |
6: putfield #24 // Field Foo$$i:I | |
9: aload_0 | |
10: iconst_0 | |
11: putfield #32 // Field j:I | |
14: return | |
} | |
Hi,twolfe18, what do you use to view the byte code? Thanks.
Here is my decompiled code. I just removed some methods:
def getJ = j
def iThing = i * i
def jThing = j * j
Plus
f.i
f.getJ
f.iThing
f.jThing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note the difference between iThing and jThing, one uses a field access and the other a virtual method. if you want to be able to expose your fields to the public, but want fast access with getfield, then use private[this] and write your own getter.