40.1 Introduction

If you start working with Scala you will probably quickly come across the library Scalaz. It is a very widely used set of extensions to the core language. In many cases when people talk about developing systems in Scala they actually mean a combination of Scala and Scalaz.

Scalaz is actually a very large library of extensions which could have (and do have) books dedicated just to it. Indeed, if you look at

You can find a 21-day course dedicated to Scalaz. As this book is intended as an introduction to Scala and covers much of the language, this chapter will be restricted to an introduction to Scalaz and an overview of the most useful features for you at this stage.

40.2 Obtaining Scalaz

Scalaz is not a standard part of the Scala installation. You must therefore add it yourself to your environment. At the time of writing, the current version of Scalaz is 7.2.17 for Scala 2.12.

The easiest way is to add it to your project dependencies using Maven or SBT.

To add Scalaz to your Maven project use:

<dependency>         <groupId>org.scalaz</groupId>         <artifactId>scalaz-core_2.12</artifactId>         <version>7.2.17</version> </dependency>

If you are using SBT, add the following line to your build file:

libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.2.17"

Alternatively, you can download Scalaz from

40.3 Scalaz Overview

Scalaz is a very large and exhaustive library of extensions for Scala. Its focus is on emphasizing and supporting functional programming and type correctness. Many teams therefore adopt Scalaz either because they wish to explicit its set of typesafe extensions or because they wish to further push the use of functional program (or of course both).

A significant aspect of Scala is its support for typesafe operations. These are primarily supported by the introduction of Typeclasses in Scalaz. A Typeclass is a mechanism for ad hoc, compile time, polymorphism. Note the comment about ‘compile time’ in that sentence. In standard Scala (and languages such as Java and C#) runtime polymorphism is supported. However, Scalaz supports compile time polymorphism, while the distinction may not be of that much interest to you; it does mean that at compile time you can be notified of potential issues that might only be identified at runtime due to undesirable behaviour. An example might be:

           1 == "1"

This is legal Scala but will always return false; as an Int can never equal a String. In Scalaz the ‘ === ’ operator is used to perform a compile time check on the types. Thus

           1 == "1"

will generate a compile time error (rather than allowing the runtime environment to merely execute).

From a functional programming point of view, the extensions provided by Scalaz are inspired by Haskell and the theoretical concepts behind functional programming. This can mean that, at least initially, it can seem that Scalaz is complicated and quiet abstract (which is probably true) although some aspects of the library are very straight forward to use and very useful (and these are the focus of this chapter).

There are many tutorials available online which will explore much of the theoretical side of Scala such as Monads, Functors, Applicatives, etc., and some of these are listed at the end of this chapter.

40.4 Some Useful Typeclasses

40.4.1 Equals Typeclass

Scalaz provides a typesafe equals operator that will generate a compile error if incompatible types are compared.

For example, while == and != in standard Scala will allow you to compare a String and an Int but will always return false, the Scalaz operators === and =/= operators will result in a compile time error:

As can be seen above although Scala allows the integer 1 and the string “1” to be compared, Scalaz does not.

40.4.2 Order Typeclass

Scalaz provides a very easy to use typeclass that provides for typesafe ordering. This means that instances can be compared for relative ordering but that ordering of incompatible types will now generate a runtime error:

In the above example Scala allows the integer 1 and the double 4 to be compared, whereas Scalaz does not.

The ?|? operator can also be used to compare two compatible values and returns a scalaz.Ordering object. This object is one of:

  • Ordering.LT —indicating that the first value is less than the second value

  • Ordering.EQ —indicating that the values are equal

  • Ordering.GT —indicating that the second value is greater than the first.

The output generated from this application is:

           1 < 4d: true            1 ?|? 1: EQ            1 ?|? 2: LT            2 ?|? 1: GT            Its less than

40.5 Standard Class Extensions

40.5.1 Extensions to Option

Scalaz provides a set of extensions to the Option type in Scala. These extensions make it easier to work with Options. For example, there are some convenience constructor methods that return Option types (rather than returning Some or None types). See

  • some —returns a Some instance but the specified type is Option[T]

  • none[T] —returns a None value of type Option[T]

Scalaz also provides some alternatives to the getOrElse operation available on standard Options types. These such as the ternary operator for Options do not directly have an equivalent in the standard library.

The final operator examined here is the ‘ ~ ’ operator that returns the item contained in the Option (if it is defined), otherwise it returns the Zeroth value for the type specified. If the type is an Int, then it is 0 , if it is a Boolean, then it is false, etc.

The output from this simple application is:

           x1: 20            x2: 10            x3: 5            3            0

40.5.2 Boolean Extensions

Scalaz also adds some additional functionality to the Boolean type. For example, it provides the ?| and ?? operators.

The ?| operator is a ternary operator that will return the first value following the ‘?’ if the condition is true, otherwise it returns the second value. For example,

The ?? operator returns the given argument if the condition is true, otherwise it returns the Zeroth version of the argument, thus

40.5.3 Extensions to List

Scalaz also provides some extensions to the List type. Some of these extensions are shown below.

In the above example three extensions to the List type are shown, namely:

  • tailOption—this returns a list containing the tail of the list it is applied to wrapped in an Option.

  • Intersperse—this adds the provided argument to the elements in the original list, between each of the values held in the list.

  • Powerset—this returns a list of lists that represent all combinations of the values in the original list.

Note that none of these operations affects the original list; they all generate a new list.

The output from the example is:

Some(List(20, 30)) List  (10, 1, 20, 1, 30) List  (List(a, b, c), List(a, b), List(a, c), List(a), List(b, c), List(b), List(c), List())

40.5.4 Extensions for Map

Another collection type that is extended by Scalaz is Map . As an example, the following code example illustrates altering a map within a safe manner. The example creates a simple Map and then uses the Scalaz alter operation to modify the value with the key “a”. In this case a function is applied to the value in which the value 5 is applied to the existing value. It uses the |+| which is an alias for mappend (a function that appends a value and returns the result). The mappand function takes two values of the same type and returns a value of that type (which is the result of appending them). In this case the argument f to the function is of type Option[Int] .

The second example in the above code uses a method intersectWith that determines the intersection (between keys) of two maps. In this case only the key “b” is common to the maps m1 and m3. The result returned in this case is the value held in the second map. If we wanted the value held in the first map, then we would return that value from the function passed to the intersectWith method, for example,

The output from this example is:

                m1: Map(a -> 10, b -> 20)                 m2: Map(a -> 15, b -> 20)                 m3: Map(b -> 250, c -> 300)                 m1.intersectWith(m3)((m1v,m3v) => m3v): Map(b -> 250)

40.5.5 Extensions to String

Scalaz also provides some interesting extensions to the String class.

One example is its introduction of the plural operator which tries (with some mixed success) to convert words into their plural version, for example “Day” into “Days”. It is a little naïve as the approach taken is to pluralise a String by appending an "s" unless this String ends with "y" and not one of ["ay", "ey", "iy", "oy", "uy"] in which case the 'y' character is chopped and "ies" is appended. It is possible to specify an integer to plural that indicates how many of something is being specified; 1 indicates a singular value (and thus just returns the string as is).

A more useful feature of the string extensions is the set of parse operations. These will safely parse booleans, bytes, shorts, longs, floats, doubles and ints from a string without throwing an exception if the value passed to them is not a number. Instead the operations return a Success or Failure object that wraps the result or the associated exception.

The output generated by the example application is:

           s1.plural(2): Days            Success(10.0)            Failure(java.lang.NumberFormatException: For input string: "ten")

40.6 The Other Either

Another feature of Scalaz is its provision of what is sometimes known as the other Either. Scala provides Either as a way of capture that either a successful result has been generated or not. Scalaz version provides a set of utility methods that make it easier to work with.

The Scalaz Disjunction is defined as \/[A, B] . It is right biased (as right by convention is the success element) and provides operations such as map , flatMap, etc., that work on the right side of the object.

The output from this simple example is:

           \/-(1234)            -\/(java.lang.NumberFormatException: For input string: "John")

One of the easiest ways of working with Sclacz \/[A, B] is to use the fromTryCatchNonFatal method. This will try to execute an expression. If it is successful, then the result is stored in the right side of the result. If an exception is thrown, then this is stored in the left side. The side of the value is indicated by a ‘ - ’; either to the right or left of the \/ symbol (as shown above).

40.7 Tagging

Tags can be used to create new types based on existing types. It uses the @@ symbol to tag an existing type as another type (creating a new type). This can be useful if you want to use, for example, a String to represent an ID but do not want just any old string to be used.

The following example illustrates the basic idea of using tagging to create a new type:

In this example, we use the @@ symbol to tag a String with the class MyID . This is used to define a type Id (which is actually an alias to  String @@ MyId , which expands to  @@[String, MyId] , which in turn expands to  String with Tagged[MyId] ).

Online Scalaz Resources