Scala: A look at flatMap and map on Option

As a quick Scala tip, if you haven’t worked with the flatMap on an Option much, it can help to know that flatMap’s function should return an Option, which you can see in this REPL example:

scala> Some(1).flatMap{ i => Option(i) }
res0: Option[Int] = Some(1)

You can tell this by looking at the function signature in the scaladoc for the flatMap method on the Option class:

Scala Vector informational and mathematical methods (syntax, examples) alvin May 21, 2018 - 3:11pm

This page contains a collection of examples of how to use Scala Vector class informational and mathematical methods. Note that these same methods will also work with a Scala Seq, including IndexedSeq.

Informational and mathematical methods

As the name implies, these methods let you get information about the contents of a Vector, or perform mathematical expressions on a Vector.

Using structs in JavaScript (example, syntax)

Bearing in mind that I rarely use JavaScript and I’m not an expert in it, I like the idea of using something like a C-like “struct” in my JavaScript code, so I used the following approach on a recent project. First, I define my JavaScript struct:

function Book(title, href, imageUri, description) {
    this.title = title;
    this.href = href;
    this.imageUri = imageUri;
    this.description = description;

Then I define an array of Book types:

A Scala method to run any block of code slowly

The book, Advanced Scala with Cats, has a nice little function you can use to run a block of code “slowly”:

def slowly[A](body: => A) = try body finally Thread.sleep(100)

I’d never seen a try/finally block written like that (without a catch clause), so it was something new for the brain.

In the book they run a factorial method slowly, like this:

slowly(factorial(n - 1).map(_ * n))

FWIW, you can modify slowly to pass in the length of time to sleep, like this:

def slowly[A](body: => A, sleepTime: Long) = try body finally Thread.sleep(sleepTime)
How to use partially applied functions in Scala alvin March 7, 2018 - 8:16pm

Problem: You want to eliminate repetitively passing variables into a Scala function by (a) passing common variables into the function to (b) create a new function that’s pre-loaded with those values, and then (c) use the new function, passing it only the unique variables it needs.

Solution: The classic example of a partially applied function begins with a simple sum function:

How to define Scala methods that take complex functions as parameters (syntax) alvin March 7, 2018 - 8:14pm

Problem: You want to define a Scala method that takes a function as a parameter, and that function may have one or more input parameters, and may also return a value.

Solution: Following the approach described in the previous recipe, define a method that takes a function as a parameter. Specify the function signature you expect to receive, and then execute that function inside the body of the method.