Open In App

Scala | Uniform Access Principle

Last Updated : 08 Apr, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
In Scala, a programming abstraction is implemented which is called as Uniform Access Principle, which states that the annotations utilized to retrieve a property of a Class is equivalent for both methods and variables. This principle was imposed forward by Bertrand Meyer. The principle simply means that the notation used to access a feature of a class shouldn’t differ depending on whether it’s a method or an attribute . Some points to note:
  • Using this Principle attributes and functions with no parameters can be accessed by identical syntax.
  • The definition of a function with no parameters can be transformed to "var" or vice-versa.
  • This Principle is more aligned to the object oriented programming.
Example : Scala
// Scala program for Uniform
// Access Principle

// Creating object
object Access
{

    // Main method
    def main(args: Array[String])
    {

        // Creating array
        val x : Array[Int] = Array(7, 8, 9, 10, 45)

        // Creating String
        val y = "GeeksforGeeks"

        // Accessing length of an 
        // array
        println(x.length)

        // Accessing length of a
        // String
        println(y.length)
    }
}
Output:
5
13
Now, We know that the length of an array is a variable and length of a string is a method in the Class "String" but we accessed both of them in same way. Example : Scala
// Scala program for Uniform
// Access Principle

// Creating object
object Access
{

    // Main method
    def main(args: Array[String])
    {

        // Creating a list
        val x = List(1, 3, 5, 7, 9, 10)

        // Creating a method
        def portal = {

        "Geeks" +"for" + "Geeks"

        }

        // Accessing size of a
        // method
        println(portal.size)

        // Accessing size of a
        // variable
        println(x.size)
    }
}
Output:
13
6
Here, also a variable and a method both are accessed in a same manner.

Next Article
Article Tags :

Similar Reads