Posts in the “scala” category

A Scala CLI 'watch' script

In the spirit of giving back whatever I can to the Scala community, here’s a very little shell script that I named scw that lets you run the scala-cli command with its --watch option:

#!/bin/sh

# NAME:    scw
# VERSION: 0.1
# PURPOSE: a script that works like a “Unix alias
#          that requires a command-line argument”.

filename=""
if [ $1 ]
then
    filename="$1"
else
    echo "PURPOSE: Run 'scala-cli <filename> --watch'"
    echo "USAGE:   scw <filename>"
    exit 1
fi

scala-cli $filename --watch

I use it with the exercises in my Learn Scala 3 The Fast Way! book, and I’ll include it with that book’s Github repository shortly.

I created this script because I wanted something like a Unix alias to shorten that scala-cli command. When you’re typing that command for more than 80 lessons, every character counts. :) It works like this:

$ scw Functions.sc
4
6
Watching sources, press Ctrl+C to exit.
Compiling project (Scala 3.1.1, JVM)
Compiled project (Scala 3.1.1, JVM)
4
8

Thanks to Scala CLI, that command runs my script, and when I change the script it automatically runs it again.

Functional error handling in Scala

[toc]

Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? This lesson demonstrates the techniques of functional error handling in Scala.

A Scala “functional programming style” To-Do List application written with Cats

NOTE: If you read my previous article (a Scala functional programming style To-Do List application), the new content in this article starts down at The Scala/FP Code section.

Back when I was writing Functional Programming, Simplified I started to write a little Scala/FP “To-Do List” application that you can run from the command line, based on a similar application in the Learn You A Haskell For Great Good book. For reasons I don’t remember, I decided not to include it in the book, and forgot about it until I started using GraalVM (“Graal”) recently.

In functional programming, side effects are kind of a big deal

A Scala 2.10 (and newer) implicit class example (how to add new functionality to closed classes)

Scala FAQ: Can you share an example of how to create an implicit class in Scala 2.10?

Sure. As the question implies, the implicit class functionality changed in Scala 2.10, so let's take a look at the new syntax.

Background

Rather than create a separate library of String utility methods, like a StringUtilities class, you want to add your own behavior(s) to the String class, so you can write code like this:

[toc hidden:1]

A collection of 100+ Scala String examples

[toc]

This page contains a collection of over 100 Scala String examples, including string functions, format specifiers, and more. I don’t provide too many details about how things work in these examples; this is mostly just a collection of examples that can be used as a Scala String reference page or cheat sheet. (I do show the output of most examples.)

Scala: How to use higher-order functions (HOFs) with Option (instead of match expressions)

I originally wrote a long introduction to this article about how to work with the Scala Option/Some/None classes, but I decided to keep that introduction for a future article. For this article I’ll just say:

  • idiomatic Scala code involves never using null values
  • because you never use nulls, it’s important for you to become an expert at using Option, Some, and None
  • initially you may want to use match expressions to handle Option values
  • as you become more proficient with Scala and Options, you’ll find that match expressions tend to be verbose
  • becoming proficient with higher-order functions (HOFs) like map, filter, fold, and many others are the cure for that verbosity

Given that background, the purpose of this article is to show how to use HOFs rather than match expressions when working with Option values.

What is “Functional Programming”?

[toc]

Note: This is an excerpt from my book, Functional Programming, Simplified. (No one has review this text yet. All mistakes are definitely my own.)

Defining “Functional Programming”

It’s surprisingly hard to find a consistent definition of functional programming. As just one example, some people say that functional programming (FP) is about writing pure functions — which is a good start — but then they add something else like, “The programming language must be lazy.” Really? Does a programming language really have to be lazy (non-strict) to be FP? (The correct answer is “no.”)

I share links to many definitions at the end of this lesson, but I think you can define FP with just two statements:

A collection of Scala ‘flatMap’ examples

Scala flatMap FAQ: Can you share some Scala flatMap examples?

Sure. When I was first trying to learn Scala, and cram the collections' flatMap method into my brain, I scoured books and the internet for great flatMap examples. Once I had a little grasp of it I started creating my own examples, and tried to keep them simple.

Using flatMap on a list of Strings

The following examples show the differences between map and flatMap on a sequence of String:

[toc hidden:1]

Scala 3 dates: How to parse strings into dates (LocalDate, DateTimeFormatter)

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.12, Parsing Strings Into Dates.

Problem

While using Scala (2 or 3), you need to parse a string into one of the date/time types introduced in Java 8.

Solution

If your string is in the expected format, pass it to the parse method of the desired class. If the string is not in the expected (default) format, create a formatter to define the format you want to accept.

Scala 3: Creating New Date and Time Instances

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.9, Creating New Date and Time Instances.

Problem

You need to create new date and time instances using the Date and Time API that was introduced with Java 8.

Solution

Using the Java 8 API you can create new dates, times, and date/time values. Descriptions of common Java 8 Date and Time classes provides a description of some of the new classes you’ll use (from the java.time Javadoc), all of which work in the ISO-8601 calendar system.

Some Scala Exception ‘allCatch’ examples

At the time of this writing there aren’t many examples of the Scala Exception object allCatch method to be found, so I thought I’d share some examples here.

In each example I first show the "success" case, and then show the "failure" case. Other than that, I won’t explain these, but hopefully seeing them in the REPL will be enough to get you pointed in the right direction:

A Scala/JavaFX WebSocket client

As a brief note today, I started to create a little Scala/JavaFX WebSocket client based on the Java-WebSocket project. I initially created it to test my Play Framework WebSocket example. I had hoped to be able to easily get to the server response request headers, but atm I don’t see a way to do that.

That being said, this is what the Scala/JavaFX WebSocket client currently looks like:

A Scala/JavaFX WebSocket client

And here’s its source code: