Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using private[this] on an object member in Scala

Tags:

scala

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?

like image 643
joesan Avatar asked Dec 09 '22 03:12

joesan


2 Answers

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.

like image 95
dwickern Avatar answered Dec 28 '22 18:12

dwickern


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
like image 44
som-snytt Avatar answered Dec 28 '22 17:12

som-snytt