Posts in the “scala” category

Book: Learn Functional Programming The Fast Way! (FP for OOP developers)

MARCH, 2023: This book was previously named, Learn Functional Programming Without Fear, but I have renamed it to Learn Functional Programming The Fast Way. I think this name is more reflective of the ZIO and Cats Effect libraries being easier to learn than ever before (without having to know category theory), and the name is also consistent with my other book, Learn Scala 3 The Fast Way.

NOV., 2022: My new book, Learn Functional Programming Without Fear, is currently an Amazon Java and functional programming #1 new release. The book is now available in three formats:

PDF Format
$10 (USD) on Gumroad.com

Learn Functional Programming The Fast Way! (PDF Version)

Paperback
$30 on Amazon

Learn Functional Programming The Fast Way (Paperback)

Kindle
$10 on Amazon

Learn Functional Programming The Fast Way! (Kindle Edition)

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

[toc]

(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"

The Scala-CLI/Coursier cache location on a Mac/macOS system

As a brief note, my Mac/macOS system disk was pretty full, so I started looking at things I could delete easily. One thing I found is that the Scala-CLI/Coursier cache is location in this Mac directory:

/Users/al/Library/Caches/Coursier

I don’t know yet if it’s safe to delete anything in that directory/folder, but it’s using 7.2GB of space, so I’m about to look into it.

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]

Scala List class examples: range, fill, tabulate, appending, foreach, more ...

Scala List FAQ: Can you share some Scala List class examples?

The Scala List class may be the most commonly used data structure in Scala applications. Therefore, it's very helpful to know how create lists, merge lists, select items from lists, operate on each element in a list, and so on.

In this tutorial, I'll share examples of the most common List operations (methods).

A Scala Spring Framework dependency injection example

Curious about how well Scala would play with the Spring Framework, I created a small Scala/Spring dependency injection example project, which I'm sharing here.

The short answer is that Scala worked just fine with Spring, but it also showed me that I still have plenty to learn about inheritance in Scala.

My Spring applicationContext.xml file

I copied a Spring applicationContext.xml file from another project, then whittled it down to these bare essentials:

[toc hidden:1]

How to iterate over Scala Lists with foreach and for

[toc]

Scala List/sequence FAQ: How do I iterate over a Scala List (or more generally, a Scala sequence) using the foreach method or for loop?

There are a number of ways to iterate over a Scala List using the foreach method (which is available to Scala sequences like List, Array, ArrayBuffer, Vector, Seq, etc.) and for comprehension, and I'll show a few of those approaches here.

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

[toc]

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. An instance of the Scala Some class
  2. 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.