サーチ…


前書き

Scalaのスコープは、値( defvalvarまたはclass )がどこからアクセスできるかを定義します。

構文

  • 宣言
  • 私的宣言
  • プライベート[this]宣言
  • プライベート[fromWhere]宣言
  • 保護された宣言
  • protected [fromWhere]宣言

パブリック(デフォルト)スコープ

デフォルトでは、スコープはpublicです。値はどこからでもアクセスできます。

package com.example {
  class FooClass {
    val x = "foo"
  }
}

package an.other.package {
  class BarClass {
    val foo = new com.example.FooClass
    foo.x // <- Accessing a public value from another package
  }
}

プライベートスコープ

スコープがプライベートである場合、現在のクラスまたは現在のクラスの他のインスタンスからのみアクセスできます。

package com.example {
  class FooClass {
    private val x = "foo"
    def aFoo(otherFoo: FooClass) {
      otherFoo.x // <- Accessing from another instance of the same class
    }
  }
  class BarClass {
    val f = new FooClass
    f.x // <- This will not compile
  }
}

プライベートなパッケージ固有のスコープ

プライベート値にアクセスできるパッケージを指定できます。

package com.example {
  class FooClass {
    private val x = "foo"
    private[example] val y = "bar"
  }
  class BarClass {
    val f = new FooClass
    f.x // <- Will not compile
    f.y // <- Will compile
  }
}

オブジェクトのプライベートスコープ

最も限定的なスコープは「オブジェクトプライベート」スコープで、オブジェクトの同じインスタンスからその値にアクセスできるようにします。

class FooClass {
  private[this] val x = "foo"
  def aFoo(otherFoo: FooClass) = {
    otherFoo.x // <- This will not compile, accessing x outside the object instance
  }
}

保護された範囲

protectedスコープでは、現在のクラスの任意のサブクラスから値にアクセスできます。

class FooClass {
  protected val x = "foo"
}
class BarClass extends FooClass {
  val y = x // It is a subclass instance, will compile
}
class ClassB {
  val f = new FooClass
  f.x // <- This will not compile
}

パッケージ保護範囲

package protected scopeは、特定のパッケージ内の任意のサブクラスからのみ値にアクセスできるようにします。

package com.example {
  class FooClass {
    protected[example] val x = "foo"
  }
  class ClassB extends FooClass {
    val y = x // It's in the protected scope, will compile
  }
}
package com {
  class BarClass extends com.example.FooClass {
    val y = x // <- Outside the protected scope, will not compile
  }
}


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow