In the following code:
object MyObj {
private[this] def myMethod = .....
}
My understanding of the this modifier to the access modifiers (private, public... etc.,) is that the presence of this makes it specific to that instance! In the case above we only have one instance. So isn't this redundant?
A private
member (which is called class-private) is accessible from both the class and its companion object. A private[this]
member (called object-private) is truly not accessible from outside the companion object.
class MyObj {
MyObj.classPrivate
MyObj.objectPrivate // error: symbol is not accessible
}
object MyObj {
private def classPrivate = ???
private[this] def objectPrivate = ???
}
So in short, the keyword is not redundant here.
The qualifier disables generation of accessors:
scala> object X { private var v = 42 ; def x = v * 2 }
defined object X
scala> object Y { private[this] var v = 42 ; def x = v * 2 }
defined object Y
scala> :javap -pr X
Binary file X contains $line3.$read$$iw$$iw$X$
Compiled from "<console>"
public class $line3.$read$$iw$$iw$X$ {
public static final $line3.$read$$iw$$iw$X$ MODULE$;
private int v;
public static {};
private int v();
private void v_$eq(int);
public int x();
public $line3.$read$$iw$$iw$X$();
}
scala> :javap -pr Y
Binary file Y contains $line4.$read$$iw$$iw$Y$
Compiled from "<console>"
public class $line4.$read$$iw$$iw$Y$ {
public static final $line4.$read$$iw$$iw$Y$ MODULE$;
private int v;
public static {};
public int x();
public $line4.$read$$iw$$iw$Y$();
}
scala> :javap -prv X#x
public int x();
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: invokespecial #24 // Method v:()I
4: iconst_2
5: imul
6: ireturn
LocalVariableTable:
Start Length Slot Name Signature
0 7 0 this L$line3/$read$$iw$$iw$X$;
LineNumberTable:
line 7: 0
scala> :javap -prv Y#x
public int x();
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: getfield #18 // Field v:I
4: iconst_2
5: imul
6: ireturn
LocalVariableTable:
Start Length Slot Name Signature
0 7 0 this L$line4/$read$$iw$$iw$Y$;
LineNumberTable:
line 7: 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With