Access Modifiers
Access modifiers decide who can use something, like rooms with different locks. Things are open to everyone unless you mark them private or protected.
In this page:
Syntax
class ClassName {
private var hidden: Type = value
protected var inherited: Type = value
var visible: Type = value
}
Access Modifiers
Scala members are public by default unless marked private (visible only within the class) or protected (visible within the class and its subclasses).
private[this] restricts access even further, to only the specific instance, not just the class. Encapsulating internal state as private and exposing it through public methods is standard OOP practice, same as in most other languages.
Note:
Scala members are public by default -- unlike some languages where you must explicitly opt into public visibility.
Example: Access Modifiers
class Account(startingBalance: Double) {
private var balance = startingBalance
def deposit(amount: Double): Unit = {
balance += amount
}
def getBalance(): Double = balance
}
object Main extends App {
val acc = new Account(100)
acc.deposit(50)
println(acc.getBalance())
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to access a
privatemember from outside the class, such asacct.balance, which gives a compile error. - Assuming
privatehides members from a companion object, when a companion object can access the class's private members. - Making everything
publicby leaving out modifiers, exposing fields that should only change through methods likedeposit.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: