private[this] 与在 scala 中没有 val/var 的情况下给出参数

private[this] Vs giving parameters without val/var in scala

我知道在 class 中将 val/var 标记为私有 [this] 和提供不带 val/var 的 class 参数是相同的。

 class ABC (x:Int){..}

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

在这两种情况下,x 只能由同一对象的构造函数和方法访问。我的理解正确吗?

谢谢!

两者都

import scala.reflect.runtime.universe._

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

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

生产

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

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

产生

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

所以你问题的答案

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

为阳性。

您可以检查 class ABC(x: Int) 是否创建了一个 (private[this]) 字段来验证您可以使用 this

访问它
class ABC(x: Int) {
  this.x
}

但需要强调的是,Scala 规范并未指定 class ABC(x: Int) 中的 x 字段或者它是 不是一个字段。这只是 Scalac 和 Dotty 编译器的当前行为。

Get the property of parent class in case classes

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.

嗯,这不一样,因为 class ABC(x: Int) 你有一个接受 Int.

的构造函数