Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

Scala’s Self-recursive Types

One of the advantages of using a statically typed language is that you can use the type system to enforce some constraints. Scala provides self-recursive types, aka F-bounded polymorphic types that–along with self types–let you put powerful constraint to your type definitions.

Self-recursive type definition

Terminology apart, let me show you one of the use cases where this could be useful. Consider the following example which does not use a self-recursive type:

1
2
3
trait Doubler[T] {
  def double: T
}
1
2
3
case class Square(base: Double) extends Doubler[Square] {
  override def double: Square = Square(base * 2)
}

So far so good, the compiler will not complain. The problem is that it won’t complain even if you write something outrageous like the following code:

1
2
3
4
5
case class Person(firstname: String, lastname: String, age: Int)

case class Square(base: Double) extends Doubler[Person] {
  override def double: Person = Person("John", "Smith", 42)
}

You want to avoid something like that by enforcing a compile-time check. Enters a self-recursive type:

1
2
3
trait Doubler[T <: Doubler[T]] {
  def double: T
}

By using this definition of Doubler you’re saying: “Hey, if someone tries to extends Doubler with a type which doesn’t extend Doubler in turn (hence self-recursive), do not compile it”. In this case the previous definition of Square, which extends Doubler[Person], doesn’t compile.

Note that self-recursive types are not specific to Scala. Indeed Java uses them too. Take, for example, the Enum definition:

1
2
3
public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable {
...
}

E extends Enum<E> in Javanese means exactly E <: Enum[E]

Self type definition

F-bounded polymorphic types are of great help but sometimes they are not enough to enforce the constraints you need. Indeed, the previous definition of Doubler has still one problem. Consider the next code:

1
2
3
4
5
6
7
8
9
10
11
trait Doubler[T <: Doubler[T]] {
  def double: T
}

case class Square(base: Double) extends Doubler[Square] {
  override def double: Square = Square(base * 2)
}

case class Apple(kind: String) extends Doubler[Square] {
  override def double: Square = Square(5)
}

Can you spot the problem? Look at the Apple definition, it extends Doubler[Square] instead of Doubler[Apple].

This code compiles because it respects the constraint put by the Doubler definition. Indeed Square extends Doubler so it can be used in Apple. Sometimes this is what you want in which case the self-recursive type will do. In cases when you don’t want this to happen a self type can work this out:

1
2
3
trait Doubler[T <: Doubler[T]] { self: T =>
  def double: T
}

Now if you try to compile the previous definition of Apple the compiler will complain by saying something like:

1
2
3
4
error: illegal inheritance;
 self-type Apple does not conform to Doubler[Square]'s selftype Square
       case class Apple(kind: String) extends Doubler[Square] {
                                              ^

Conclusions

If you’re thinking: “Come on! I would never extend Apple that way because I know what I meant when I wrote my Doubler abstraction. I don’t need then the self type annotation and, since I know what I’m doing, I don’t need the self-recursive type either”. Well you may be right but I’d have two objections:

  1. Generally you are not the only one working on a project and, anyway, a good rule of thumb is to design your software as if you’re designing a public API. In this case you want to be sure no one will use your API in the wrong way.

  2. Compilers are implemented by smart guys, generally. Having the compiler help by your side is always a good thing in my humble opinion.

Are there alternatives to this type of problems? Yes indeed, Type Classes, which is by the way the option I prefer. But this is another story for a future post.

Scala DSL for Currency-related Operations

A simple internal DSL in Scala for money-related operations

Source code: Scala DSL for money-related operations

This Domain-Specific Language (DSL) lets you perform operations among different currencies, by transparently doing all internal conversions. The conversion map is injected implicitly by the client code.

Usage Example

Here’s a simple usage example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import com.lambdista.money._
import com.lambdista.money.Currency._

object Main {

  def main(args: Array[String]): Unit = {

    val conversion: Conversion = Map(
      (GBP, EUR) -> 1.270,
      (EUR, USD) -> 1.268,
      (GBP, USD) -> 1.611
    )

    implicit val converter = Converter(conversion)

    val sumAndConversion1 = 100.001(USD) + 200(EUR) to GBP
    println(s"sumAndConversion1: $sumAndConversion1")

    val sumAndConversion2: Money = 100(USD) + 210.4(EUR) to EUR
    println(s"sumAndConversion2: $sumAndConversion2")

    val sum = 100.001(USD) + 200(EUR)
    val simpleConversion = sum(GBP)
    println(s"simpleConversion: $simpleConversion")

    val sumWithSimpleNumber = 100(USD) + 23.560
    println(s"sumWithSimpleNumber: $sumWithSimpleNumber")

    val multiplicationWithSimpleNumber = 100(USD) * 23
    println(s"multiplicationWithSimpleNumber: $multiplicationWithSimpleNumber")

    val usd = Currency("USD")

    val multiplication = 100(usd) * 23(EUR)
    println(s"multiplication: $multiplication")

    val divisionWithSimpleNumber = 100(USD) / 23
    println(s"divisionWithSimpleNumber: $divisionWithSimpleNumber")

    val comparison = 100(USD) > 90(EUR)
    println(s"100 USD > 90 EUR? $comparison")

  }

}

As you can see the client code just needs two simple imports and an implicit value of type Converter in order to use the DSL. The operations shown in the previous code are only a few among the available ones. Have a look at the Money class for a complete coverage.

You can find the source code here: Scala DSL for money-related operations

Try-Success-Failure API for Java 8

Try-Success-Failure API: Java implementation of the famous Scala counterpart

Source code: Try-Success-Failure API for Java

This API is a Java implementation of Scala Try API, originally implemented by the guys at Twitter and later added to the Scala Standard Library.

The Try type represents a computation that may fail. If the computation is successful returns the value wrapped in a Try.Success otherwise returns the java.lang.Exception wrapped in a Try.Failure.

To use Try you need to call the Try.apply(FailableSupplier) method passing in a lambda with the same signature used for a common java.util.function.Supplier. Indeed FailableSupplier is just a java.util.function.Supplier with a throws Exception added to its get method.

For example, Try can be used to perform division on a user-defined input, without the need to do explicit exception-handling in all of the places that an exception might occur.

An important property of Try shown in the divide method of the MainExample class is its ability to pipeline (chain if you prefer) operations, catching exceptions along the way thanks to its flatMap method. If you are not a seasoned functional programming geek concepts such as flatMap/map might not be easy to grasp at first. However you’ll get used to them and, in the end, you’ll love them. Moreover you’re going to encounter these methods more and more often since some important Java 8 classes already implement them (e.g. java.util.Optional and java.util.stream.Stream. Anyway for the moment just take for granted that to pipeline more than two operations, say N, you just need to chain them by using N - 1 flatMap calls and a last call to map. E.g.: Suppose you have 3 variables (x, y and z) being of type Try and you just want to sum them up. The code you need for doing that is the following:

1
x.flatMap(a -> y.flatMap(b -> z.map(c -> a + b + c)))

Apart from map and flatMap, Try has many other useful methods. See the TryTest class for a thorough coverage of all methods.

Usage example

1
2
3
4
5
6
7
8
9
10
11
12
System.out.println("Integer division");
System.out.println("Enter the dividend press Return and then enter the divisor: ");
Scanner dividend = new Scanner(System.in);
Scanner divisor = new Scanner(System.in);

Try<Integer> num = Try.apply(dividend::nextInt);
Try<Integer> denom = Try.apply(divisor::nextInt);

Try<Integer> result = num.flatMap(x -> denom.map(y -> x / y));
Try<String> resultTryStr = result.map(i -> "The result of division is: " + i);
String resultStr = resultTryStr.getOrElse("You must've divided by zero or entered something that's not an Int. Try again!");
System.out.println(resultStr);

In the previous example if you enter two valid integers with the second one–the divisor–being different from zero then the code prints out The result of division is: $RESULT, where $RESULT is the division between the first and the second number. On the other hand, if you either enter non valid integers–such as a string–or the second number is zero then you’ll get the message You must've divided by zero or entered something that's not an Int. Try again! printed out.

Anyway, as I already said, see the TryTest class for a thorough coverage of all methods.

Final Notes

Any criticism/suggestion is more than welcome!

Source code: Try-Success-Failure API for Java

Combine JavaScript and a Template Engine for Flexible Web Apps

Combine the power and simplicity of the TrimPath template engine with JavaScript and Ajax to develop next-generation web applications.

Template engines (TEs) can be very useful in web development scenarios where you need to generate and format text automatically according to specific processing rules. These engines can also help you build your applications based on the Model-View-Controller (MVC) pattern, making them more robust and maintainable than applications based on spaghetti code. Most programming languages provide built-in or third-party TEs. Java, for example, has Velocity and FreeMarker, among others. For PHP, Smarty is the most used TE.

Go to developer.com to read the rest of the article: Combine JavaScript and a Template Engine for Flexible Web Apps.

Script.aculo.us Controls: Do Your Web Users a Favor

Learn how to integrate Script.aculo.us web controls into your web applications to make the end-user experience more pleasant.

In a previous DevX article, I wrote about the JavaScript framework Prototype, which aims to ease the development of dynamic web applications. That article ended with just a few words about Script.aculo.us, which is a fantastic UI library based on Prototype. This article gives Script.aculo.us its due by examining the web controls it provides: autocompleters, sliders, and in-place editors.

Script.aculo.us is a pretty big library, so no single article can cover it completely. However, the knowledge you will gain will enable you to leverage the power of Script.aculo.us web controls to improve the end-user experience.

Go to DevX to read the rest of the article: Script.aculo.us Controls: Do Your Web Users a Favor.

Will Your Next Web Application Be a Google Gadget?

Learn how to leverage the Google Gadget API to make your web applications more reachable. As an example, you’ll see how to build a real-world gadget that fetches and displays the DevX feeds.

Since AJAX first appeared, developer interest in JavaScript has increased exponentially—and toolsets for building functionality in JavaScript have burgeoned as well. One of the latest tools for JavaScript-related development is Google Gadgets. Many web sites already provide gadgets built with the Google tools, and you can, too. This article shows you how to develop a Google Gadget that fetches DevX RSS feeds and displays them to the user.

Go to DevX to read the rest of the article: Will Your Next Web Application Be a Google Gadget?.

The Productivity Perks Behind Prototype’s Popularity

Learn how to leverage the popular Prototype JavaScript framework to speed up your AJAX-based development. You’ll see how to use JavaScript in an object-oriented way.

The Prototype home page claims that “Prototype is a JavaScript framework that aims to ease the development of dynamic Web applications.” By using many object-oriented paradigms such as class-driven development and inheritance to enable JavaScript application development, Prototype completely accomplishes its aim. In fact, this framework contains a lot of useful functionalities, which you cannot help but apply to every application you develop once you’ve started using them.

Prototype’s main claim to fame is its rich AJAX (Asynchronous JavaScript and XML) library, which simplifies the now popular Web development technique for making non-blocking calls to the server through JavaScript. (It topped the recent Ajaxian.com 2006 Survey as the most popular AJAX framework.) Of course, everything you can do with Prototype you also can do using plain JavaScript—upon which Prototype is built. But why would you want to complicate your life? For example, which would you rather type to accomplish the same task: document.getElementById(“myElement”) or $(“myElement”)? If you answered $(“myElement”), then read the remainder of this article for an in-depth discussion of some useful Prototype functions—$ is just one.

Go to DevX to read the rest of the article: The Productivity Perks Behind Prototype’s Popularity.

Speed Up Your AJAX-based Apps With JSON

Find out how to improve your Web application performance by leveraging AJAX and JSON. In particular, you’ll see the advantages of using JSON over XML as a lightweight JavaScript data-interchange format.

JSON stands for JavaScript Object Notation and is a lightweight data-interchange format. Because it is text-based it is easy for humans to read and write, and it has a regular syntax that’s easy to parse programmatically. JSON is basically a subset of JavaScript and, as you’ll see, is even easier to parse than XML.

Go to DevX to read the rest of the article: Speed Up Your AJAX-based Apps with JSON.