Posts in the “scala” category

The Scala 3 'for' loop (for/yield) syntax and examples

Here are some examples of the Scala 3 for loop syntax, including for/do and for/yield expressions.

Scala 3 'for' loop syntax (for/do)

// single line
for i <- ints do println(i)
for (i <- ints) println(i)

// multiline
for
    i <- ints
    if i > 2
do
    println(i)

Using 'end for' with for/do

You can also add end for to the end of a Scala 3 for loop, so the previous multiline example can also look like this:

for
    i <- ints
    if i > 2
do
    println(i)
end for

Scala 3 'for' loop as the body of a method

These examples show how to use a for loop as the body of a Scala method:

import io.Source

def printLines1(source: Source): Unit =
    for line <- source.getLines do println(line)

def printLines2(source: Source): Unit =
    for line <- source.getLines
    do println(line)
    
def printLines3(source: Source): Unit =
    for line <- source.getLines
    do
        println(line)
        
def printLines4(source: Source): Unit =
    for
        line <- source.getLines
    do
        println(line)
        
def printLines5(source: Source): Unit =
    for
        line <- source.getLines
        if line.trim != ""
    do
        // a multiline `do` block
        println("in `do` block of `for`")
        println(line)

Scala 3 for/yield expressions

Here are some single-line for/yield expressions:

Scala: GraalVM native-image: Warning: Image 'ffx' is a fallback image that requires a JDK

As a brief note to self, this weekend I was trying to create a GraalVM native executable named ffx from a Scala project, and I got this error during the GraalVM native-image compilation process:

GraalVM native-image: Warning: Image 'ffx' is a fallback image that requires a JDK
for execution (use --no-fallback to suppress fallback image generation and to print 
more detailed information why a fallback image was necessary).

Then I tried to create the native image using the --no-fallback option, but that failed.

Scala type aliases (syntax, examples)

[toc]

As a little note today, in Scala 2 you can declare a type alias. Typically you do this to create a simple alias for a more complex type.

Scala 3 Update: Scala 3 also has opaque types, which we wrote about here on the docs.scala-lang.org website.

Using a type alias to simplify a complex type

For example, on this page I note a good example where someone on StackOverflow first defined a type alias named Row, and then created a second type alias named Matrix as a list of rows:

type Row = List[Int]
type Matrix = List[Row]    

The type Matrix is easier to read than this:

List[List[Int]]

This is similar to a Haskell example I remember seeing, where a Word was defined as a list of characters, a Sentence was defined as a list of words, and a Paragraph was defined as a list of sentences:

type Word = List[Char]
type Sentence = List[Word]
type Paragraph = List[Sentence]

Paragraph is certainly easier to remember than List[List[List[Char]]].

Creating a more meaningful name with a type alias

You can also create a type alias to create a more meaningful name for a type. For example, many people model money/currency using a BigDecimal, so a type alias like this makes sense:

type Money = BigDecimal

You can then use the type alias Money as a normal type in your Scala classes, objects, traits, and methods, like these examples:

def getPrice(): Money = 10.50
def doublePrice(m: Money): Money = 2.0 * m

Type alias rules

There are just a few rules to know about using type aliases in Scala. The main rule to know about a type alias is that it must be defined inside a class, object, or package object.

Another “rule” to know isn’t really a rule, but a way to think about a type alias: when you use a type alias to declare a type parameter, as with these methods:

def getPrice(): Money = 10.50
def doublePrice(m: Money): Money = 2.0 * m

the type Money is literally replaced by the compiler with its equivalent type, BigDecimal, so the compiled code becomes this:

def getPrice(): BigDecimal = 10.50
def doublePrice(m: BigDecimal): BigDecimal = 2.0 * m

Summary: Scala type aliases

I’ll write more about Scala type aliases when I can, but I hope this is enough information to get you started working with them.

Scala 3 opaque types: How to create meaningful type names

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 23.7, Creating Meaningful Type Names with Opaque Types.

Problem

In keeping with practices like Domain-Driven Design (DDD), you want to give values that have simple types like String and Int more meaningful type names to make your code safer.

Solution

In Scala 3, use opaque types to create meaningful type names. For an example of the problem, when a customer orders something on an e-commerce website you may add it to a cart using the customerId and the productId:

A Scala method to create an MD5 hash of a string

If you happen to need a Scala method to perform an MD5 hash on a string, I believe this method works as desired:

// returns a 32-character MD5 hash version of the input string
def md5HashPassword(usPassword: String): String = {
    import java.math.BigInteger
    import java.security.MessageDigest
    val md = MessageDigest.getInstance("MD5")
    val digest: Array[Byte] = md.digest(usPassword.getBytes)
    val bigInt = new BigInteger(1, digest)
    val hashedPassword = bigInt.toString(16).trim
    prependWithZeros(hashedPassword)
}

/**
 * This uses a little magic in that the string I start with is a
 * “format specifier,” and it states that the string it returns
 * should be prepended with blank spaces as needed to make the
 * string length equal to 32. Then I replace those blank spaces
 * with the character `0`.
 */
private def prependWithZeros(pwd: String): String =
    "%1$32s".format(pwd).replace(' ', '0')

The Scala ternary operator syntax

Scala FAQ: What is the Scala ternary operator syntax?

In other programming languages there is a definite, unique ternary operator syntax, but in Scala, the ternary operator is just the normal Scala if/else syntax:

if (i == 1) x else y

The beauty of this is (a) it is just the normal if/else syntax, so you don't have to remember something else, and (b) it's easy to read.

A “Minority Report” Monte Carlo simulation in Scala

This article shares the source code for a Monte Carlo simulation that I wrote in Scala. It was inspired by the movie Minority Report, as well as my own experience.

Background

For the purposes of this simulation, imagine that you have three people that are each “right” roughly 80% of the time. For instance, if they take a test with 100 questions, each of the three individuals will get 80 of the questions right, although they may not get the same questions right or wrong. Given these three people, my question to several statisticians was, “If two of the people have the same answer to a given question, what are the odds that they are correct? Furthermore, if all three of them give the same answer to a question, what are the odds that they are right?”

How to use multiple Futures in a Scala for-comprehension

If you want to create multiple Scala Futures and merge their results together to get a result in a for comprehension, the correct approach is to (a) first create the futures, (b) merge their results in a for comprehension, then (c) extract the result using onComplete or a similar technique.

An example of Scala’s `f` string interpolator

With Scala it’s common to embed variables in strings like this with the s string interpolator:

val name = "Fred"
println(s"My name is $name.")

That’s cool, but when you need to format your string, Scala gives you an even more powerful tool: the f string interpolator. Here’s an example of how I just did this in my LittleLogger logging library:

Play Framework 2.8, Scala, Slick, MySQL, and sbt (2022)

These are my notes from creating a Play Framework 2.8 project on January 2, 2022, using Scala 2.13, MySQL, and Slick. I share these notes here because I found it hard to find the correct versions of everything that needed to be used, and the correct syntax in the application.conf file. Unfortunately the Play 2.8 documentation is not up to date, so this was much harder than I expected it to be.

Scala: Akka Typed tutorial: Finding Actors with the Receptionist

Scala/Akka problem: In some situations you can’t pass an ActorRef to another actor, so you want to see how to “look up” an Akka Typed actor so you can send a message to it.

Solution

There are at least two ways to find other Akka Typed actors, and both involve using the Akka Receptionist. The example shown here in the solution shows how to find an actor asynchronously, and the example shown in the Discussion shows how to use the ask method to find another actor synchronously.

In both examples I’ll use the idea of creating an actor system that works like Amazon Echo devices. The basic idea is that a device like this has ears to listen to you, a mouth to speak to you, and a brain to do all of its work. In these examples the Brain actor will need to discover the Mouth actor.

Scala: Akka Typed tutorial: How to delegate work to child actors

Scala/Akka problem: You know that an actor that “blocks” is bad for your system, so you want to create Akka Typed actors that don’t block.

Solution

With Akka Typed, the mantra is always, “Delegate, delegate, delegate.” It’s important that high-level actors delegate work to lower-level actors, so the high-level actors can be free to receive new messages and respond to them immediately.