Access Modifiers: Scala & Java

In this post we will analyse the differences and the similarities between access modifiers in Scala and Java. Despite Scala is compatible with Java, there are some differences.


In Java there are four types of access modifiers:

  • public: this is the less restrictive access modifier. Classes, methods, inner classes and fields can be declared public. Every class in every package can access the element declared public.
  • protected: methods, inner classes and fields can be declared protected. Only subclasses or classes in the same package can access the element declared protected.
  • default: classes, methods, inner classes and fields can be declared with no access modifier. Only classes in the same package can access the element declared with no modifier.
  • private: this is the most restrictive modifier. Methods, inner classes and fields can be declared private. Only the own class can access the elements declared private. Private methods or fields existing in an inner class can be accessed by the outer class.

Let’s make it more visual:

Modifier Class Package Subclass Every class
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N


In Scala there are three types of access modifiers (default that behaves like public, protected and private) but they can be augmented with qualifiers (only protected and private can). This qualification means that access is protected or private up to a scope.

First we will explain the unqualified access modifiers:

  • default: this is the less restrictive one, it behaves like public in Java. Classes, methods, inner classes and fields can be declared with no modifier. Every class in every package can access the element declared with no modifier.
  • protected: a member declared protected can be accessed only by its subclasses. This access modifier is more restrictive than its analogous in Java.
  • private: this is the most restrictive modifier. A member declared private can be accessed only by the owner class. This also applies for inner classes. In other words a private member is visible inside the own class and inside any deeper inner class. This rule only applies downwards, so a private member defined in an inner class can not be accessed by any outer class (this is possible in Java).

Let’s see the table:

Modifier Class Package Subclass Every class
default Y Y Y Y
protected Y N Y N
private Y N N N

Right now you could be wondering how to make a member visible for any class in the same package. The answer is scoped access modifiers. As we said, private and protected access modifiers can be qualified with a name of a package or class (scope). Generally scoped private and scoped protected access modifiers behave the same way, except under inheritance when declared on class members. The scope is defined between square brackets.

When the scope of protected or private is a package, the visibility is similar to package visibility in Java (default). Given a class X defined inside the package a.b.c, a member defined with protected[a] (or private[a]) is visible within package a. If you want the same behaviour than default visibility in Java, you must specify protected[c] (or private[c]).

When the scope is a class, the visibility is similar to private with some considerations. Given a class X with an inner class Y, a member in Y defined as protected[X] (or private[X]) behaves identically to private in Java. Otherwise, when defined as protected[Y] (or private[Y]) behaves identically to private in Scala.

There is yet another scope, this, that gives the most restrictive access modifier that exists. When a member of a class is defined as protected[this] (or private[this]), it is illegal to access this member outside the object. In other words, given private[this] var foo = 3, foo only can be accessed this way:

Previously we said that scoped protected and private behave identically except under inheritance. The only difference is that scoped protected is less restrictive because, independently of the scope stated, a member defined with protected[something] is visible for any subclass, while when defined with private[something] is not.


Sorting Algorithms Comparison and Quicksort example

Today I’ve remembered those days back in University, when we learned Algorithms and Data Structures. Among the big amount of algorithms we studied, there were the sorting algorithms. The first algorithm introduced was the Bubble Sort, the worst efficient one. Afterwards, the most efficient algorithms were introduced: Merge Sort and Quicksort. Let’s remember the basics of these algorithms.

Bubble Sort

This is the simplest algorithm, however it’s the worst one in performance speaking. The average and worst case complexity are both O(n2). But there is good news, its complexity, for the best case, is only O(n). Here there is an animation that explains how it works: Bubble Sort Animation.

Merge Sort

The Merge Sort algorithm is better than Bubble Sort. The average and worst case complexity is O(nlogn). The best case (when the array is sorted) is also O(nlogn), but with some optimizations can be reduced to O(n). Here you can find another animation Merge Sort.


The Quicksort algorithm is usually faster than Merge Sort, despite they have the same average case complexity O(nlogn). However, the complexity for the worst case is O(n2), with some improvements it can be reduced. Here there is an animation: Quicksort.

Implementation Quicksort

After this brief comparison between sorting algorithms, let’s see the implementation of Quicksort algorithm in Java and Scala.


This is the implementation in Java of the Quicksort algorithm:

public static void sort(int[] xs){ sort(xs,0,xs.length-1); } public static void sort(int[] xs, int left, int right){ int pivot = xs[(left+right)/2]; int i = left; int j = right; while(i <= j){ while(xs[i] < pivot){ i++; } while(xs[j] > pivot){ j++; } if(i<=j){ int sw = xs[i]; xs[i] = xs[j]; xs[j] = sw; i++; j--; } } if(left < j){ sort(xs,left,j); } if(j < right){ sort(xs,i,right); } }


First the algorithm in a no functional way, as you could see, this implementation is equivalent to Java’s:

def sort(xs: Array[Int]) { def swap(i: Int, j: Int) { val t = xs(i); xs(i) = xs(j); xs(j) = t } def sort1(l: Int, r: Int) { val pivot = xs((l + r) / 2) var i = l; var j = r while (i <= j) { while (xs(i) < pivot) i += 1 while (xs(j) > pivot) j -= 1 if (i <= j) { swap(i, j) i += 1 j -= 1 } } if (l < j) sort1(l, j) if (j < r) sort1(i, r) } sort1(0, xs.length - 1) }

And now, let’s rewrite it in a functional way:

def sort(xs: Array[Int]): Array[Int] = { if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <))) } }

Getters & Setters and its goodness and evilness

If you are a DZone reader, you will have read many posts about getters and setters and its evilness. Getters and setters are the response to an old Object Oriented principle which says that object’s implementation must not be exposed. On the other hand, there is also another old principle called Uniform Access Principle which says that client code should not be affected by a decision to implement an attribute as a method or field. Unfortunately, Java doesn’t follow this last principle.

Don’t Expose the Implementation

Currently, the most used IDE’s can generate the getters and setters for fields. Sometimes this doesn’t help, and developers automatically generate unnecessary getters and/or setters. This next example could be seen as a situation where generating getters and setters automatically is a bad practice:

package com.wordpress.j2eethoughts.ooPrinciples; public class Odometer{ private BigDecimal total; private BigDecimal partial; public Odometer (){ total = BigDecimal.ZERO; partial = BigDecimal.ZERO; } public BigDecimal getTotal(){ return total; } public void setTotal(BigDecimal total){ = total; } public BigDecimal getPartial(){ return partial; } public void setPartial(BigDecimal partial){ this.partial = partial; } }

Now let’s explain because this is a bad practice. Maybe at a first glance, you may think that this implementations satisfies the principle of not expose the internal implementation of the object. Unfortunately, this is not true, everything is exposed. There isn’t much difference between this implementation with getters and setters and the hypothetical implementation with public fields. In addition, you can do illegal things with this implementation, as decrement the number of Kilometres of the Odometer. The unique advantage between this implementation and one with public fields is that you could attach some functionality in any function, like logging, checking permissions…

A more correct implementation for this class would be:

package com.wordpress.j2eethoughts.ooPrinciples; public class Odometer{ private BigDecimal total; private BigDecimal partial; public Odometer (){ total = BigDecimal.ZERO; partial = BigDecimal.ZERO; } public BigDecimal getTotal(){ return total; } public BigDecimal getPartial(){ return partial; } public void resetPartial(){ partial = BigDecimal.ZERO; } public void increment(BigDecimal inc){ partial.add(inc.abs()); total.add(inc.abs()); } }

This class implementation ensures that nothing wrong is done with the Odometer, Kilometres can only increase and you can’t rig the Odometer decreasing the total amount of Kilometres made.

Uniform Access Principle

As we have explained before, Java doesn’t satisfy the Uniform Access Principle, for this reason we will explain it using Scala. The client code must not be affected if the developer decides to implement an attribute as a method or as a field. For illustrating this example we will use a Circle class. There will be two different implementations for the attributes perimeter and area.

package com.wordpress.j2eethoughts.uap import Math.Pi class CircleVal (radius : Int){ val perimeter = 2 * Pi * radius val area = Pi * radius * radius } class CircleDef (radius : Int){ def perimeter = 2 * Pi * radius def area = Pi * radius * radius }

The client uses these classes exactly the same way in both implementations. The client doesn’t care if the developer had decided to implement these attributes as methods or as fields.

package com.wordpress.j2eethoughts.uap object Main { def main(args : Array[String]) : Unit = { val c1 = new CircleVal(4) println(c1.perimeter) println(c1.area) val c2 = new CircleDef(4) println(c2.perimeter) println(c2.area) } }

This post is not supposed to decide about the evilness or goodness of getters and setters, its only intention is to think about its use. So, we would be very glad if after reading this post, you think twice before ask your IDE to automatically generate the getters and setters.

The power of Lists in Scala

Let me introduce you the piece of code possibly most used in history:

for(int i = 0; i < list1.length() ; i++){ //do something }

Since java 1.5 we have a more concise way to do the same, the foreach iteration:

for(Object o : list1){ //do something }

If we want to create a list with all elements of list1 that fulfill some condition, we need some boilerplate code:

List list2 = new ArrayList(); for(Integer i : list1){ if(i > 0){ list2.add(i); } }

Every time we want to find elements that fulfill some condition, we need to copy this code except for the third line, which has to be adapted.

One of the main goals of Scala is to reduce the boilerplate code that exists in our Java code. To accomplish this goal, there are some higher-order operators, which can take a function as a parameter. Some useful higher-order operators will be described in this post.


The filter operator takes as operands a list of type List[T] and one function of type T => Boolean called predicate. This operator returns a new list with all elements of the original list for which the predicate is true. With this operator we can, in only one line, do the same that the Java code.

scala> val list1 = List(1,3,4,0,-1,6)
list1: List[Int] = List(1, 3, 4, 0, -1, 6)
scala> val list2 = list1 filter (_ > 0)
res0: List[Int] = List(1, 3, 4, 6)

The list created will contain only the elements of list1 that are greater than 0.


This operator is very similar to filter, except that returns the first element for which the predicate is true. Actually it returns an optional value; this is the Scala approach for nullable objects. If at least one element makes predicate true, it will return Some(T), otherwise None. This approach ensures in compilation time that no optional values are considered as common variables of type T.

scala> list1 find (_ > 0)
res1: Option[Int] = Some(1)
scala> list1 find (_ > 100)
res2: Option[Int] = None


The partition operator returns a pair of lists. The first one includes all elements that satisfies the predicate. The second includes all elements for which the predicate is false.

scala> list1 partition (_ > 0)
res3: (List[Int], List[Int]) = (List(1, 3, 4, 6),List(0, -1))


The takeWhile operator iterates the original list until it finds one element that doesn’t satisfy the predicate, all this elements are added in the result list. In other words, it returns the longest prefix such that every element satisfies the predicate.

scala> list1 takeWhile (_ > 0)
res4: List[Int] = List(1, 3, 4)


The dropWhile operator iterates the original list until it finds one element that doesn’t satisfy the predicate, the remaining elements are added in the result list. In other words, it drops the longest prefix such that every element satisfies the predicate.

scala> list1 dropWhile (_ > 0)
res5: List[Int] = List(0, -1, 6)

These are few operations that can help us in our everyday coding. The less lines we code, the less chances of introducing errors we have. In addition, we can avoid repeating the most repetitive and error-prone code.

Scala: Implementing Factory

In a previous post we explained the Design Pattern Factory Method and how it differs from the Builder Pattern. Now we will explain how to implement this pattern in Scala. However, first we need to learn a new concept in Scala: the Companion Objects.

Companion Object

Previously, we said that a Companion Object could be seen, from a Java point of view, as a Static Class.

A Companion Object is an Object that shares the same name and source file with another Class or Trait. A Trait could be seen as a Java Interface.

The Companion Object is useful for implementing utility methods, factories, apply and unapply methods…

When it does exist a Companion, the class is called Companion Class and the object is called Companion Object. This name’s collision is possible because they don’t share the same namespace. While classes are stored in the type namespace, objects are stored in the term namespace. You can read the Scala language specifications here.

Implementing Queue Factory in Java

We want to implement a factory that produces different types of shapes depending on the number of sides given.
First of all, we need the abstract class. In this example it could be an interface, but we could also add some other common properties as fill colour, line colour…

package com.wordpress.j2eethoughts.factory; public abstract class Shape { public abstract double getArea(); public abstract double getPerimeter(); }

We will work with two different kinds of shapes: triangle and rectangle. Here comes the code for Triangle:

package com.wordpress.j2eethoughts.factory; public class Triangle extends Shape { private double ab; private double bc; private double ac; public Triangle(double ab, double bc, double ac) { super(); this.ab = ab; this.bc = bc; = ac; } @Override /** * Heron's way */ public double getArea() { double s = getPerimeter()/2; return Math.sqrt(s*(s-ac)*(s-ab)*(s-bc)); } @Override public double getPerimeter() { return ab+bc+ac; } }

And this is the source for Rectangle:

package com.wordpress.j2eethoughts.factory; public class Rectangle extends Shape { private double height; private double length; public Rectangle(double height, double length){ super(); this.height = height; this.length = length; } @Override public double getArea() { return height*length; } @Override public double getPerimeter() { return (height*2)+(length*2); } }

And finally, the source of the factory:

package com.wordpress.j2eethoughts.factory; public class ShapeFactory { public static Shape getShape(double len1, double len2, double len3){ return new Triangle(len1,len2,len3); } public static Shape getShape(double len1, double len2){ return new Rectangle(len1,len2); } }

After this, we can test this classes with this little application:

package com.wordpress.j2eethoughts.factory; public class Main { public static void main(String[] args) { Shape sh1 = ShapeFactory.getShape(32.34, 23); System.out.println(sh1.getArea()); System.out.println(sh1.getPerimeter()); Shape sh2 = ShapeFactory.getShape(5, 3, 4); System.out.println(sh2.getArea()); System.out.println(sh2.getPerimeter()); } }

Implementing Queue Factory in Scala

If we want to implement this shape factory in Scala we will need only one source file. We will use a companion class Shape and a companion object Shape, this last one will act as a factory. Therefore, the concrete implementations of Shape will be private classes of the companion object. With this approach, we hide any concrete implementation of Shape from the client.

This is the source code for the companion class and object.

package com.wordpress.j2eethoughts.queue import scala.Math.sqrt abstract class Shape { def perimeter : Double def area : Double } object Shape { private class Triangle (ab : Double, bc : Double, ac : Double) extends Shape{ override val perimeter = ab + bc + ac private val s = perimeter / 2 override val area = sqrt(s*(s-ac)*(s-ab)*(s-bc)) } private class Rectangle (height : Double, length : Double) extends Shape{ override val perimeter = height * 2 + length * 2 override val area = height * length } def apply(ab : Double, bc : Double, ac : Double) : Shape = new Triangle(ab,bc,ac) def apply(height : Double, length : Double) : Shape = new Rectangle(height,length) }

I would like to make some considerations about this implementation. When we override a method, the keyword override is mandatory, it won’t compile if it’s not included. Furthermore, it’s possible to override a method with a variable. If you look at the concrete classes, the abstract methods defined in Shape are overridden with a val.

Now we will test the Shape Factory:

package com.wordpress.j2eethoughts.queue object Main { def main(args : Array[String]) : Unit = { val sh1 = Shape (32.34, 23) println(sh1.area) println(sh1.perimeter) val sh2 = Shape (3,4,5) println(sh2.area) println(sh2.perimeter) } }

Scala: Overloading Operators

If you come from Java I have just caught your attention. If you are a C++ developer you might be not surprised.

In Scala, every operator is actually a method. The difference between methods and operators is how you use them. When you write:

val = 3 + 5

Scala calls the method + defined in Int:

val = (3).+(5)

In the first example + is used as operator, in the second one, + is used as a method.
As said, every operator is a method, which means that we can call any method as an operator. For instance, this two instructions are equivalent:

val test1 = “Alice” startsWith “A”
val test2 = “Alice”.startsWith(“A”)

After reading this, you might be wondering: Scala doesn’t really have operator overloading, it is only method overloading. Well, maybe it’s true, but from the language point of view, it is operator overloading!

There are three types of operators, infix, prefix and postfix. In Scala you can implement these three kinds, but there are some restrictions about the prefix and postfix operators.


In infix notation, you put the operator between the objects. This kind of operators could take two or more operators. When having more than two, all but the first go after operator between parenthesis.
Now let’s do a real example where it could be useful this infix operator overloading.

class Angle (d: Int, m: Int, s: Int) { require (d < 360 && m <60 && s < 60) val degree: Int = d val minute: Int = m val second: Int = s def + (that: Angle) : Angle = { val sec = second + that.second val min = minute + that.minute + (sec /60) val deg = degree + + (min /60) new Angle (deg % 360,min % 60,sec % 60) } def + (deg: Int) : Angle = new Angle (degree + deg % 360, minute, second) def - (that: Angle) : Angle = { val thisSecs = degree * 3600 + minute * 60 + second val thatSecs = * 3600 + that.minute * 60 + that.second val dif = if(thisSecs <= thatSecs) thisSecs - thatSecs else thatSecs - thisSecs val min = dif / 60 val deg = min /60 new Angle (deg , min % 60, dif % 60) } override def toString = degree+ "º "+minute+"' "+second+"''" }

After creating this class, we can add and subtract angles as follows:

val angle1 = new Angle(40,30,35)
val angle2 = new Angle(30,52,50)
val angle3 = angle1 + angle2
println(angle1 – angle2)
println(angle2 – angle1)
println(angle3 – angle1)

And the result is:

71º 23′ 25”
9º 37′ 45”
9º 37′ 45”
30º 52′ 50”

This example above is only a proof of concept of operator overloading. Maybe it’s not programmed in a functional way, but I’ve done my best. Any comments are appreciated.


In prefix notation, you put the operator before the object. In Scala, the prefix operators can only take one operator, this is called unary operator. The only identifiers that can be used in unary prefix operators are +, , ! and ~. If you need to define a prefix operator, for instance, !, you must implement a method called unary_!.


In postfix notation, you put the operator after the object. This kind of operators are also unary. Unlike the prefix operators, in postfix operators there is no restriction about the names of the methods/operators. The convention about postfix operators is invoking the operators without parenthesis only if the operator has no side effects, otherwise, you might include them. For example, method toLowerCase defined in String should be invoked without parenthesis and println() should be invoked with parenthesis because it writes to the Console.

Scala: Arrays, Lists, Sets and Maps

Despite all Scala code is translated to Java code, there are some differences between Scala Collections and Java Collections. In this post we will try to explain four types of collections: Arrays, Lists, Sets and Maps.


In Scala, in contrast to Java, there is an Array object and it can be created in the same way as Java does. However, the syntax differs. The first one is the classical way to create an object.

var classicWay = new Array[String](3)
classicWay(0) = “The”
classicWay(1) = “classic”
classicWay(2) = “way”

There are two important differences to notice. The way to specify the type of the Array is [] instead of <>. The other one is the way to instance the array, in Scala we use the () instead of []. There is also another way to create and initialize an Array, which is less verbose and more compact.

var compactWay = Array(“I”,”like”,”this”,”way”)

As it can be seen, there is no need to specify the type of the Array, the compiler will infer that the type is String. Here there is another difference, we use the companion class to get an instance of Array. Companion classes will be explained in another post, but they can be seen as static classes or utility classes.
Obviously, we can’t access a position of the Array with the [] operator, instead, the () operator is used. For instance:

compactWay(0) = “We”

It will be transformed into:



Lists in Scala are always immutable (in Java they can be mutable), they are designed to enable a functional style programming. That means that, once created, a Scala List can’t be modified. But there are operators on Lists, so maybe you would be wondering why there are operators on Lists if they are immutable objects. As in Strings, when you invoke any operation on a List, another List is created and returned when an operator is applied. Maybe, the two main operators are ::: and :: . The first one is the operator for list concatenation. The second one is the operator to prepend an element to a List. Yes, you read it well: prepend (in Scala you can’t append elements to a list). This is because prepend an element at the beginning of a list is a constant-time operation, whereas append is a linear-time operation. Usually, the owner of an operation is the left operand, but in :: the owner is the right operand. Here there are some examples.

val list1 = List(“This”,”is”)
val list2 = List(“a”,”list”)
val list3 = list1 ::: list2
val list4 = “Hey!” :: list3

List1 and list2 remain immutable, they didn’t change. List3 is a new list resulting of concatenating list1 and list2. In list4, the String “Hey!” is prepended to list3. The complete api of List object can be found here.


There are two kinds of Sets, the immutable and the mutable one. The difference between mutable and immutable objects is that when an object is immutable, the object itself can’t be changed. The most known immutable object in Java is String: once you have created a String, it remains the same until it is destroyed.

By default, Scala uses the immutable Set. If you want to use the mutable Set, you’ll have to import the class. The hierarchy of the Set is the following:

Hierarchy for the Scala Set object

It’s not a problem to change between mutable and immutable collections, since all of them share the same contract. In most cases, no change will be necessary.

You can create a Set in the same way you create a List. The most useful operations are + and +=, but the second one it’s only available in mutable Sets. In the immutable Sets  mySet += “foo”  is transformed to mySet = mySet.+(“foo”). Here there is a simple example of immutable sets:

var trilogies = Set(“The Godfather”, “Lord of the Rings”)
trilogies += “Millennium”

In this example, a new Set is created in line 2. If we import the mutable Set, in this same line, the trilogies set will be modified:

import scala.collection.mutable.Set
var trilogies = Set(“The Godfather”, “Lord of the Rings”)
trilogies += “Millennium”


As in Sets, there are two kinds of Maps, the immutable and the mutable ones. The hierarchy of Map is analog to Map’s hierarchy:
Hierarchy of Scala Set
There are two ways to create a Map in Scala, one of them can only be used with the mutable Maps:

import scala.collection.mutable.Map
var steps = Map[Int, String]()
steps += (1 -> “Go straight on”)
steps += (2 -> “Take the second turn on the left”)
steps += (3 -> “It’s opposite the hairdresser”)

Obviously, this Map needs to be mutable, because it has been modified since its creation. Ok, we know how to create mutable Maps, but how immutable Maps can be created?

var steps = Map (1 -> “Go straight on”, 2 -> “Take the second turn on the left”, 3 -> “It’s opposite the hairdresser”)

Here again, there is no need to specify the type of the Array, the compiler will infer that the type is Int for the keys and String for the values. The operator -> is useful for creating Tuples. A Tuple can be seen as an array of objects, but they don’t need to share the same type.