Access Modifiers Available in Scala

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:

  1. private:

    • Members marked as private are accessible only within the class or object in which they are defined.

    • Example:

      scala
      class 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.

  2. protected:

    • Members marked as protected are accessible within the class and its subclasses (derived classes).

    • Example:

      scala
      class MyBaseClass { protected val protectedField = 42 } class MySubClass extends MyBaseClass { def accessProtected(): Unit = { println(protectedField) } }

      In this example, protectedField is accessible within MyBaseClass and MySubClass.

  3. 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:

      scala
      package 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.

  4. 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:

      scala
      package 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.


Search
Related Articles

Leave a Comment: