MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Scope

Examples

Public (default) scope


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 another package
 }
}

A private scope


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 same class
 }
 }
 class BarClass {
 val f = new FooClass
f.x // <- This will not compile
 }
}

A private package-specific scope


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 // <- Will compile
 }
}

Object private scope


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 outside the object instance
 }
}

Protected scope


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 // <- This will not compile
}


Conclusion

In this page (written and validated by ) you learned about Scala Scope . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Self types.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.