Tutorial by Examples

By default, the scope is public, the value can be accessed from anywhere. 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 anothe...
When the scope is private, it can only be accessed from the current class or other instances of the current class. package com.example { class FooClass { private val x = "foo" def aFoo(otherFoo: FooClass) { otherFoo.x // <- Accessing from another instance of the sam...
You can specify a package where the private value can be accessed. 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 // <- Wil...
The most restrictive scope is "object-private" scope, which only allows that value to be accessed from the same instance of the object. class FooClass { private[this] val x = "foo" def aFoo(otherFoo: FooClass) = { otherFoo.x // <- This will not compile, accessing x...
The protected scope allows the value to be accessed from any subclasses of the current class. 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 // <...
The package protected scope allows the value to be accessed only from any subclass in a specific package. 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 ...

Page 1 of 1