Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-26 23:19:48 Viewed : 280
Access Modifiers Available in Scala:
In Scala, access modifiers are used to control the visibility and accessibility of members (fields, methods, or types) within classes and objects. There are three main access modifiers available:
private
:
Members marked as private
are accessible only within the class or object in which they are defined.
Example:
scalaclass MyClass { private val privateField = 42 private def privateMethod(): Unit = { println("This is a private method.") } def accessPrivate(): Unit = { println(privateField) privateMethod() } }
In this example, privateField
and privateMethod
are accessible only within the MyClass
class.
protected
:
Members marked as protected
are accessible within the class and its subclasses (derived classes).
Example:
scalaclass MyBaseClass { protected val protectedField = 42 } class MySubClass extends MyBaseClass { def accessProtected(): Unit = { println(protectedField) } }
In this example, protectedField
is accessible within MyBaseClass
and MySubClass
.
public
(default):
In Scala, if no access modifier is specified, the member has package-level visibility, which means it is accessible within the same package.
Example:
scalapackage mypackage class MyClass { val publicField = 42 } object MyObject { def accessPublicField(instance: MyClass): Unit = { println(instance.publicField) } }
In this example, publicField
is accessible within the mypackage
package.
private[X]
and protected[X]
:
You can use private[X]
and protected[X]
to specify that a member is accessible within a specific enclosing scope. X
represents the enclosing scope, which can be a class, object, or package.
Example:
scalapackage mypackage class MyClass { private[mypackage] val privateField = 42 } object MyObject { def accessPrivateField(instance: MyClass): Unit = { println(instance.privateField) } }
In this example, privateField
is accessible within the mypackage
package because of the private[mypackage]
modifier.
These access modifiers help in encapsulating and controlling the visibility of members in your Scala code, promoting good software design practices and encapsulation of data and functionality.