Posts in the “scala” category

Scala tip: How to extract a field from a sequence of objects to create a new sequence

As a brief Scala tip, a fun thing you can do with the map method on Scala sequences (Array, List, Seq, Vector, etc.) is to convert a sequence of objects into a sequence of something else, typically extracting a field from the original object to create the new sequence.

For instance, imagine that you have a case class named Person that has two constructor parameters, firstName and lastName:

Benefits of sealed traits in Scala (like enum in Java)

As a quick note about traits in Scala, this StackOverflow page makes a few good points about sealed traits:

  • sealed traits can only be extended in the same file
  • this lets the compiler easily know all possible subtypes
  • example: the compiler can emit warnings if a match/case expression is not exhaustive
  • use sealed traits when the number of possibly subtypes is finite and known in advance
  • they can be a way of creating something like an enum in Java

For functional programming sealed traits also offer one really big advantage:

  • they help you define algebraic data types, or ADTs

Sealed trait examples

Examples of things that can be sealed traits are days in the week, months in a year, and the suits in a deck of cards.

The first answer from that SO page shows a simple example of how to write a sealed trait:

sealed trait Answer
case object Yes extends Answer
case object No extends Answer

This article on noelwelsh.com about algebraic data types and sealed traits is also helpful.

Scala: A simple Akka “Futures” example

Akka Futures FAQ: Can you share a simple example that shows how to use an Akka Future?

Sure. To fix a problem in my Sarah application I needed to be able to run some operations concurrently. After digging through the Akka Actors documentation I found that you can run simple operations as a Future, almost as easily as this:

A complete Scala `Future` example from the Scala Cookbook

There are a number of ways to work with Scala Futures, and I provide examples of those approaches in the Scala Cookbook.

If you’re new to Futures, a fun exercise is to try to determine what happens in your code when you use a certain technique. For instance, when you look at the following Scala source code, what do you think it will print?

A look at how exceptions work with Scala Futures and the onComplete ‘Failure’ case

Here’s a little example of how exceptions work with Scala Futures, specifically looking at the onComplete ‘Failure’ case.

In this example I start three Futures that run for different lengths of time, and the shortest-running Future throws an exception:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}

object ScalaFuturesAndExceptions extends App {

    val startTime = currentTime

    val f1 = Future {
        sleep(2000)
        1
    }
    val f2 = Future {
        sleep(550)
        throw new Exception("Ka-boom!")
        2
    }
    val f3 = Future {
        sleep(1000)
        3
    }

    val result = for {
        r1 <- f1
        r2 <- f2
        r3 <- f3
    } yield (r1 + r2 + r3)

    result.onComplete {
        case Success(x) => {
            // the code won't come here
            println(s"\nresult = $x")
        }
        case Failure(e) => {
            // the code comes here because of the intentional exception
            val finishTime = currentTime
            val delta = finishTime - startTime
            System.err.println(s"delta = $delta")
            System.err.println("Failure happened!")
            // just a short message; i don't care about the full exception
            System.err.println(e.getMessage)
        }
    }

    // important for a little parallel demo: keep the main 
    // thread of the jvm alive
    sleep(4000)

    def sleep(time: Long) = Thread.sleep(time)
    def currentTime = System.currentTimeMillis()

}

When I run this App, the Failure case isn’t reached for 2008 ms, just a bit longer than the run time of the longest-running Future, f1. Here’s the output:

delta = 2008
Failure happened!
Ka-boom!

This tells me that the exception in f2 causes the code to go to the Failure case of onComplete, but, it doesn’t get there until f1 finishes running. More specifically, the exception thrown by f2 doesn’t cause any part of the process to short-circuit after 550 ms. You can adjust the sleep times in the futures to demonstrate this for yourself.

I was just working on a Scala application to combine a few Futures and then work with the result using onComplete, and needed to see the effect that exceptions have on the process. So I created this example, and thought I’d share the results here so it might help someone else.

Update: the order matters

I didn’t think to test this initially, but if I change the order of the Futures in the for-expression, putting f2 first:

val result = for {
    r2 <- f2  //the exception-throwing future, runs 550ms
    r1 <- f1
    r3 <- f3
} yield (r1 + r2 + r3)

the output is different:

delta= 558
Failure happened!
Ka-boom!

In this example, the for-expression short-circuits immediately after f2 throws its exception after 550 ms.

In the real world there may be no way for you to know which Future will return (or throw an exception) first, but this hard-coded example shows that the order is important. (Note that if you remove the exception from f2, the code runs in just over 2000 ms, which confirms that the three futures run in parallel in the success case.)

Scala: When the sum of a list is a very large number

As a brief note, I knew that the sum function I wrote in my book on Scala and functional programming would return a wrong value if the sum of the integers in a list was greater than Int.MaxValue, and I was curious how the built-in sum method on lists handled the same problem. It turns out that it works in the same way.

So, if you need to sum a list of integers that may exceed Int.MaxValue, you might need to write a sum function that calculates and returns the sum as a Long. (The same is true for Float and Double.)

12 ScalaTest tutorials

As I’ve written before, when I finished writing the Scala Cookbook it ended up being about 140 pages longer than my editor wanted, and I had to cut some content from the book. Unfortunately the chapter on “Logging & Testing” was one of the victims of the cut, but I’m glad to say that I’ve finally taken the time to convert that material to HTML. As a result, here are links to the 12 ScalaTest tutorials in that chapter:

“Notes,” a Scala + JavaFX demo application

I wrote a little “Notes” application using Scala and JavaFX to go along with my “Hello, Scala” tutorial. If you’d like to see how it works, here’s a two-minute video:

The source code for the project is at this Github URL:

I won’t describe the application here because a) the video is the best way to show how it works, and b) I include a lengthy README file with the source code.

The build process

The build process works on MacOS. It only relies on sbt assembly and javapackager, so I hope it can be easily adapted to work on Windows. In the project’s README file I also discuss how to run the application on Linux.

Take a look at it!

If you’re new to Scala and interested in a relatively small but complete application you can experiment with, I hope this project is helpful to your Scala learning experience.

Scala idiom: Prefer immutable code (immutable data structures)

(I originally wrote this blog post in 2012, and it seems like it has held up well over time.)

One great thing I’ve learned from Scala and functional programming over the last few months is this: 

Make your variables immutable, unless there’s a good reason not to.

“Immutable” means that you can’t change (mutate) your variables; you mark them as final in Java, or use the val keyword in Scala. More important than you not changing your variables is that other programmers can’t change your variables, and you can’t change theirs.