Scala: Abstract Types

The basic idea of abstract typing in Scala is leaving undefined some types when implementing a new abstract class. This types will be defined on subclasses. Additionally, you can specify some restrictions about the hierarchy of this unknown type as: Must be subclass of or Must be superclass of. This is called lower and upper bounds.
To show the potential of this tools, the same example will be developed with four different approaches. The following objects must be modelled:

  • Generic trash.
  • Different kinds of trash, must inherit from the abstract one.
  • An abstract recycling container. Must contain common logic.
  • Different kinds of recycling containers.
  • At least one recycling container must inherit from a non-abstract one.

Simple and buggy solution

Here there is the implementation of the trash and its hierarchy. There is one generic trash called Trash, and two specializations Paper and Glass. Finally, there’s a subtype of Glass, which is WhiteGlass.

public class Trash{} public class Paper extends Trash{} public class Glass extends Trash{} public class WhiteGlass extends Glass{}

This is the simplest way to implement a generic recycling container. It should contain some logic which is not relevant for this example. The main method takes an object of type Trash. This decision will be revealed as simply wrong when implementing the subclasses.

public abstract class RecyclingContainer{ public abstract void fill(Trash trash); //some common logic. }

When creating the subtype for paper container, we realize that the previous abstract class was a bad choice. We can’t override the method taking Paper instead of Trash.

public class PaperContainer extends RecyclingContainer{ @Override public void fill(Paper paper){} }

The only thing that can make this class compile is creating a method fill that takes Trash.

public class RecyclingContainer{ public void fill(Trash trash){} }

Obviously, this solution is very buggy. In only two lines we can do something forbidden.

PaperContainer cont = new PaperContainer(); cont.fill(new Glass()); //glass in a paper container!!!

Java Generics Solution I

As using a simple solution is not working, the complexity of the code must be increased. We will create a class using generics. We want an abstract recycling container being able to carry all types of trash. This class will use Generics and the method fill will take an object of type E (any class inheriting from Trash).

public abstract class RecyclingContainer<E extends Trash>{ public abstract void fill(E trash); //some common logic. }

PaperContainer and GlassContainer will extend this abstract class delimiting the genetic type E to the proper kind of trash.

public class PaperContainer extends RecyclingContainer<Paper>{ public void fill(Paper paper){} } public class GlassContainer extends RecyclingContainer<Glass>{ public void fill(Glass glass){} }

However, this solution could not accomplish the 5th goal.

public class WhiteGlassContainer extends GlassContainer{ public void fill(WhiteGlass whiteGlass){} //won't compile }

Java Generics Solution II

Increasing again the complexity of this solution we reach the most robust option.
We will keep RecyclingContainer as it is but we will modify its subclasses. This new subclasses will lay also on the use of generics. Every fill method will take an object of the undefined type E.

public class PaperContainer<E extends Paper> extends RecyclingContainer<E>{ public void fill(E paper){} } public class GlassContainer<E extends Glass> extends RecyclingContainer<E>{ public void fill(E glass){} } public class WhiteGlassContainer<E extends Glass>; extends GlassContainer<E>{ public void fill(E whiteGlass){} }

Using this classes in a correct way, it’s easy to recycle properly:

//with a glass container RecyclingContainer<Glass> container = new GlassContainer<Glass>(); //you can add glass container.fill(new Glass()); //and white glass container.fill(new WhiteGlass()); //but no paper container.fill(new Paper()); //won't compile //and you can't "dress" a glass container like a generic one... RecyclingContainer<Trash> nonComp = new GlassContainer<Glass>(); //won't compile

However, if the developer of the client side doesn’t use generics properly, some forbidden actions can happen in runtime.

//he haven't heard about Generics! RecyclingContainer buggy = new PaperContainer(); buggy.fill(new Paper()); //and he managed to ruin the recycling plant buggy.fill(new Glass());//compiles, but throws a ClassCastException

Scala Approach

Scala provides a more robust solution to this problem. The abstract container will be created with an unknown type, called SuitableTrash in this case.

abstract class RecyclingContainer{ type SuitableTrash <: Trash def fill(trash : SuitableTrash) } class PaperContainer extends RecyclingContainer{ type SuitableTrash = Paper def fill(trash : Paper) {} } class GlassContainer extends RecyclingContainer{ type SuitableTrash = Glass def fill(trash : Glass) {} } class WhiteGlassContainer extends RecyclingContainer{ type SuitableTrash = WhiteGlass def fill(trash : WhiteGlass) {} }

This solution is safer and even inexperienced developers can’t break the logic of these classes.
* As Volker noticed, there was a problem in the code pasted, WhiteGlassContainer must extend RecyclingContainer. This means that we can’t accomplish last point of the requirements. Suggestions are welcome.

//You can fill the glass container with all types of glass val container = new GlassContainer container fill (new Glass) container fill (new WhiteGlass) //but no with paper container fill (new Paper) //won't compile //Trying to John Buggy's issue val buggy : RecyclingContainer = new GlassContainer buggy fill (new Paper) //won't compile //however neither this won't compile buggy fill (new Glass) //won't compile

In conclusion, Java provides powerful tools for checking types and avoid runtime exceptions. However, they are only applied if the developer coding the client class is programming using them. Additionally, Java is verbose enough to make things a little more complicated. Scala instead, offers a simpler and cleaner solution for the same problem which is safer than the Java one.

All-Code-Edges: 2010 in review

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image

A Boeing 747-400 passenger jet can hold 416 passengers. This blog was viewed about 12,000 times in 2010. That’s about 29 full 747s.

In 2010, there were 13 new posts, not bad for the first year! There were 10 pictures uploaded, taking up a total of 232kb. That’s about a picture per month.

The busiest day of the year was September 28th with 1,109 views. The most popular post that day was Introduction to: Patterns of Design (III).

Where did they come from?

The top referring sites in 2010 were dzone.com, reddit.com, twitter.com, en.wordpress.com, and Google Reader.

Some visitors came searching, mostly for scala hello world, scala overloading, j2eethoughts, python mutable vs. immutable, and scala operator overloading.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Introduction to: Patterns of Design (III) September 2010
1 comment

2

Getters & Setters and its goodness and evilness November 2010
9 comments

3

Scala: Hello World! September 2010
11 comments

4

Scala: Implementing Factory November 2010
4 comments

5

Scala: Overloading Operators October 2010
2 comments

Access Modifiers: Scala & Java (II – Java Examples)

In our last post, we discussed about the access modifiers in Java and in Scala. As btilford noticed, there were no examples in that post, this post is supposed to cover the Java part.

In order to better understand how access modifiers works, we have to introduce the main classes. There will be one public class and one with the default access modifier.

Main Classes

package com.wordpress.j2eethoughts.accessModifiers.a; public class PublicFooClass { public int publicBar=0; protected int protectedBar=0; int defaultBar=0; private int privateBar=0; public void doStuff(){ PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar); System.out.println(pubFoo.defaultBar); System.out.println(pubFoo.privateBar); } public void doStuff2(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } }
package com.wordpress.j2eethoughts.accessModifiers.a; class DefaultFooClass { public int publicBar=0; protected int protectedBar=0; int defaultBar=0; private int privateBar=0; public void doStuff(){ DefaultFooClass defFoo = new DefaultFooClass(); System.out.println(defFoo.publicBar); System.out.println(defFoo.protectedBar); System.out.println(defFoo.defaultBar); System.out.println(defFoo.privateBar); } public void doStuff2(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } }

These two classes haven’t any compilation error. Now it’s time to make the compiler talk.

Basic Use

package com.wordpress.j2eethoughts.accessModifiers.a; public class TestClass { public static void test(){ //public class PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar); System.out.println(pubFoo.defaultBar); System.out.println(pubFoo.privateBar);//does not compile! //default class DefaultFooClass defFoo = new DefaultFooClass(); System.out.println(defFoo.publicBar); System.out.println(defFoo.protectedBar); System.out.println(defFoo.defaultBar); System.out.println(defFoo.privateBar);//does not compile! } }

Logically, the private fields are not visible for this TestClass. Protected, default, and public fields are visible because all classes lay in the same package.
If we move this class to another package, the compiler will complaint again.

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers .a.PublicFooClass; public class TestClass { public static void main(){ //public class PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar);// does not compile! System.out.println(pubFoo.defaultBar);// does not compile! System.out.println(pubFoo.privateBar);// does not compile! //default class DefaultFooClass defFoo = new DefaultFooClass();// does not compile! System.out.println(defFoo.publicBar);// does not compile! System.out.println(defFoo.protectedBar);// does not compile! System.out.println(defFoo.defaultBar);// does not compile! System.out.println(defFoo.privateBar);// does not compile! } }

The DefaultFooClass is not visible at all for this class, because they don’t share the same package. The same rule applies for the protected and default fields of PublicFooClass.

Inheritance

There is another scope we haven’t analysed yet, the visibility in inheritance. We will extend the PublicFooClass in two different packages, discovering so the different ways that compiler complaints.
Firstly, we will implement a class extending PublicFooClass laying in the same package:

package com.wordpress.j2eethoughts.accessModifiers.a; public class SubPubFooClass extends PublicFooClass { public void doStuff(){ PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar); System.out.println(pubFoo.defaultBar); System.out.println(pubFoo.privateBar);// does not compile! } public void doStuff2(){ System.out.println(super.publicBar); System.out.println(super.protectedBar); System.out.println(super.defaultBar); System.out.println(super.privateBar);// does not compile! } }

As they share the same package, only private fields are not visible. So in this case, there is no difference (in visibility terms) between extending the class or not.
What will happen if the subclass lays in a different package?

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers.a.PublicFooClass; public class SubPubFooClass extends PublicFooClass { public void doStuff(){ PublicFooClass pubFoo = new PublicFooClass(); System.out.println(pubFoo.publicBar); System.out.println(pubFoo.protectedBar);// does not compile! System.out.println(pubFoo.defaultBar);// does not compile! System.out.println(pubFoo.privateBar);// does not compile! } public void doStuff2(){ System.out.println(super.publicBar); System.out.println(super.protectedBar); System.out.println(super.defaultBar);// does not compile! System.out.println(super.privateBar);// does not compile! } }

In this case, we find some interesting compiler errors. In doStuff2 method we have the expected errors. Private fields are inaccessible by definition, and default fields are not visible because they don’t share the same package. Now, let’s focus on the first method. Why do the compiler find more errors in this case? Because the field is accessed from outside the object. In other words, the object that access this field, doesn’t own it, so it’s invisible in its eyes.

Inner Classes

In this last group of examples, we will focus on the Inner Classes and its visibility. The first thing we need is a class with some Inner Classes.

package com.wordpress.j2eethoughts.accessModifiers.a; public class FooClass { public int publicBar=0; protected int protectedBar=0; int defaultBar=0; private int privateBar=0; public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); PubBarClass pub = new PubBarClass(); ProBarClass pro = new ProBarClass(); DefBarClass def = new DefBarClass(); PriBarClass pri = new PriBarClass(); pri.doStuff(); } public ProBarClass getProBarClass(){ return new ProBarClass(); } public class PubBarClass{ public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } protected class ProBarClass{ public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } class DefBarClass{ public void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } private class PriBarClass{ private void doStuff(){ System.out.println(publicBar); System.out.println(protectedBar); System.out.println(defaultBar); System.out.println(privateBar); } } }

We have one Inner Class for each type of modifier, this way, it will be easy to analyse what is possible and what is not. In this example, we can see that it’s possible to access outer class’ private fields from the inner class and vice-versa. Afterwards, we will test the visibility of the Inner Classes.

package com.wordpress.j2eethoughts.accessModifiers.a; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.DefBarClass; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.ProBarClass; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.PubBarClass; public class TestInner { public static void test(){ PubBarClass pub = new PubBarClass(); ProBarClass pro = new ProBarClass(); DefBarClass def = new DefBarClass(); PriBarClass pri = new PriBarClass();//does not compile! } }

As this class stands in the same package, all Inner Classes but the private are accessible.
If we move this class to another package we will get more errors.

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers .a.FooClass.PubBarClass; public class TestInner { public static void test(){ PubBarClass pub = new PubBarClass(); FooClass foo = new FooClass(); ProBarClass pro = foo.getProBarClass(); //does not compile! ProBarClass pro2 = new ProBarClass();//does not compile! DefBarClass def = new DefBarClass();//does not compile! PriBarClass pri = new PriBarClass();//does not compile! } }

Only PubBarClass is visible, because this client doesn’t share neither package and ancestor with the Inner Classes. However, if we extend the ancestor class FooClass we will get different errors.

package com.wordpress.j2eethoughts.accessModifiers.b; import com.wordpress.j2eethoughts.accessModifiers.a.FooClass; public class TestInnerExtends extends FooClass { public void test(){ PubBarClass pub = new PubBarClass(); ProBarClass pro2 = getProBarClass(); ProBarClass pro = new ProBarClass();//does not compile! DefBarClass def = new DefBarClass();//does not compile! PriBarClass pri = new PriBarClass();//does not compile! } }

The instantiation of ProBarClass doesn’t compile because there is no user defined constructor, so the compiler adds automatically a protected one (the class is protected), thus it’s not visible for this client class because it doesn’t extend that ProBarClass. At this point, you would have deduced why the default and private classes are not accessible.

We hope all these examples could explain clearly what it can be done, and what can’t, with the access modifiers.

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.

Java

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

Scala

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: this.foo.

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.

Quicksort

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.

Java

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); } }

Scala

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){ this.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.

Filter

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.

Find

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

Partition

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))

TakeWhile

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)

DropWhile

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.