Posts in the “scala” category

Using the Scala Option, Some, and None idiom (instead of Java null)

A powerful Scala idiom is to use the Option class when returning a value from a function that can be null. Simply stated, instead of returning one object when a function succeeds and null when it fails, your function should instead return an instance of an Option, where the instance is either:

  1. In the success case, return an instance of the Scala Some class
  2. In the failure case, return an instance of the Scala None class

Because Some and None are both children of Option, your function signature just declares that you're returning an Option that contains some type (such as the Int type shown below). At the very least, this has the tremendous benefit of letting the user of your function know what’s going on.

Scala 3: An apply/factory method that takes a varargs/tuple parameter

Here’s a brief Scala 3 example that shows how to:

  1. Create a companion object,
  2. Create an apply method in that companion object that acts as a factory method,
  3. Define that apply method to take a varargs tuple parameter, and
  4. Create new Person instances using that factory method.

Here’s the complete source code for this example:

How to append when writing to a text file in a Java or Scala application

As a quick Scala/Java tip, to append to a file when writing to a text file in a Scala or Java application, create your FileWriter with the append flag set to true, like this:

val bw = new BufferedWriter(new FileWriter(new File("/tmp/file.out"), true))  // <-- 'true'
bw.write("Hello, world\n")
bw.close

FileWriter takes two arguments, so that code might be easier to read when it’s formatted like this:

val bw = new BufferedWriter(
    new FileWriter(
        new File("/tmp/file.out"),
        true
    )
)
bw.write("Hello, world\n")
bw.close


Note: Appending to a text file with Scala 3

As a quick update, a great thing about Scala 3 is that you can get rid of all those new keywords, so the first part of that last example looks like this in Scala 3:

val bw = BufferedWriter(
    FileWriter(
        File("/tmp/file.out"),
        true
    )
)

Scala: A “sum of the squares” algorithm using map/sum and foldLeft

As a quick Scala fold/reduce example, I just needed to write a “sum of the squares” algorithm for a “Pearson Correlation” function I’m working on, and initially wrote it like this using map and sum:

val sumOfTheSquares = movieRatingsMap.values
                                     .map(rating => Math.pow(rating, 2))
                                     .sum

If you know Scala, and know that movieRatingsMap is a Map of movies and my ratings of those movies, I think that line of code is fairly easy to read. That line can also be written like this:

Scala 3, Scala CLI, JDBC, and SQL (examples)

As a brief “note to self” today, here are two examples of how to perform SQL queries with Scala 3, using (a) plain JDBC, and also (b) using a little Scala 3 library known as SimpleSQL. These examples use Scala CLI, which as I have mentioned before, makes these examples so much easier to share with you.

A Unix shell script to clean all SBT subdirectories

In a recent attempt at freeing up some disk space, I wrote this little Unix shell script to go through all of my Scala/SBT project directories, and run the sbt clean command in each directory:

#!/bin/sh

# WARNING: make sure you have backed up your files
# and directories before running this script.
for file in `cat sbt_dirs`
do
    dir=`dirname $file`
    echo "WORKING ON $dir"
    cd $dir
    sbt clean
    cd -
done

This script assumes that you have a list of the desired subdirectories in a file named sbt_dirs.

Sadly, I forgot to check the before and after disk space comparison, so I can only guess that it helped by deleting all the SBT project and target subdirectories it generates.

A Scala method to run any block of code slowly

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

def slowly[A](body: => A): 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): A =
    try
        body
    finally
        Thread.sleep(sleepTime)

Passing a block of code to a function in Scala (callbacks)

I've posted a lot of Scala source code examples out here lately, and as I keep trying to learn more about passing one function to another function in Scala (function callbacks), here's another example showing how you can use Scala's functional programming approach to clean up some Java Swing code:

Scala: How to build custom control structures with types and call-by-name parameters

(This article is an excerpt from the 1st Edition of the Scala Cookbook.)

To put what you’ve learned in this chapter to use, let’s create two examples:

  1. First, you’ll create a timer method that looks like a Scala control structure, and works like the Unix time command.
  2. Second, you’ll create another control structure that works like the Try/Success/Failure classes that were included with Scala 2.10.

Example 1: Creating a Scala Timer

On Unix systems you can run a time command (timex on some systems) to see how long commands take to execute:

$ time find . -name "*.scala"

A Scala cheat sheet (reference page)

Summary: This document is a Scala cheat sheet (reference page), in HTML format.

This page is very much a work in progress, but as I've been learning Scala, I've been creating all sorts of little notes, and I'm now trying to organize them into this Scala cheat sheet. These notes are based on the excellent books, Programming in Scala (Odersky, Spoon, and Venners), and Programming Scala (O'Reilly).

[toc hidden:1]