Scala Tutorials Part #14 - Uniform Access Principle in Scala


Uniform Access Principle

This is part 14 of the scala tutorial series. Check here for the full series.

Index

Introduction

The Uniform access principle is a programming concept that goes simply as

All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation.

It was put forth by Bertrand Meyer in his book called Object oriented software construction. This is not necessarily a functional programming concept, for instance you would not find this abundantly present in haskell as this is more oriented towards OOP rather than FP.

Implementation in scala

We already saw in the scala classes article that the getters and setters can be used in the same way. Accessing methods and variables is the same in scala.

  val array : Array[Int] = Array(10,30,44)

val someString = "Testing"

println(array.length)

println(someString.length)

The same example in java leads to an error.

No uac java

In java accessing the length of an array is different from accessing the length of a string. We cannot access both in the same way because the array length is a variable and the String.length() is actually a method inside the String class.

Another example in scala.

class Runnable {

val string = "Scala 2.12 is out"

def anotherString = "Scala 2.12 is out"

}

object Runnable extends App {

val instance = new Runnable

println(instance.string)
println(instance.anotherString)

}

Namespace Collision

There is a possibility of name space collision due to the nature of how the uniform access principle works. For instance, the below example would work in java.

public class Test {

int example = 10;
public int example() {
return 10;
}

}

Something similar in scala would end up in a compilation error.

Scala namespace

The error checking is necessary since it would lead to ambiguity at the language level and the compiler throws an error to prevent it.

Summing it up


Tagged Under


Scala


Search this website...




Keeping up with blogs...

I blog occasionally and mostly write about Software engineering and the likes. If you are interested in keeping up with new blog posts, you should follow me on twitter where I usually tweet when I publish them. You can also use the RSS feed , or even subscribe via email below.

Feedio Subscribe


Share & Like

If you like this post, then you can either share/discuss/vote up on the below sites.



Thoughts ...

Please feel free to share your comments below for discussion

Blog comments powered by Disqus