1

I understand that marking a val/var as private[this] inside a class and providing a class parameter without val/var is same.

 class ABC (x:Int){..}

 class ABC {
   private[this] x:Int = 100
 }

In both the cases, x can be accessed by only the constructors and the methods of the same object. Is my understanding correct ?

Thanks!

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
user3103957
  • 636
  • 4
  • 16

1 Answers1

2

Both

import scala.reflect.runtime.universe._

reify{
  class ABC(x: Int)
}.tree

and

reify {
  class ABC(private[this] val x: Int)
}.tree

produce

{
  class ABC extends AnyRef {
    <paramaccessor> private[this] val x: Int = _;
    def <init>(x: Int) = {
      super.<init>();
      ()
    }
  };
  ()
}

And

reify{
  class ABC {
    private[this] val x: Int = 100
  }
}.tree

produces

{
  class ABC extends AnyRef {
    def <init>() = {
      super.<init>();
      ()
    };
    private[this] val x: Int = 100
  };
  ()
}

So the answer to your question

In both the cases, x can be accessed by only the constructors and the methods of the same object.

is positive.

You can check that class ABC(x: Int) does create a (private[this]) field verifying that you can access it with this

class ABC(x: Int) {
  this.x
}

But it's important to emphasize that Scala specification doesn't specify either that x in class ABC(x: Int) is a field or that it's not a field. This is just current behavior of Scalac and Dotty compilers.

Get the property of parent class in case classes

Disambiguate constructor parameter with same name as class field of superclass

Do scala constructor parameters default to private val?

Scala Constructor Parameters

I understand that marking a val/var as private[this] inside a class and providing a class parameter without val/var is same.

Well, it's not the same because with class ABC(x: Int) you have a constructor accepting Int.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66