Posts in the “scala” category

Scala: A Laminar/CSS div/elements/settings example

As a brief note to self, here’s some Laminar source code that shows how to create a div in Laminar, as well as some settings/elements in that div, as well as one way to handle a reactive button click:

Laminar 101: A “Hello, world” example (static)

I recently started a new Scala project that uses the Scala/Scala.js Laminar library for frontend development (i.e., as a JavaScript replacement).

Laminar is a library that’s built on top of Scala.js to let you build “reactive” web applications with observables, and in this tutorial I’ll show how to create a static “Hello, world” application from scratch. Once we get past these basics, I’ll show in Part 2 of this series how to create a reactive single-page application (SPA) with Laminar.

Scala 3: Using Java Collections in Scala

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.10, Using Java Collections in Scala.

Problem

You’re using Java classes in a Scala application, and those classes either return Java collections, or require Java collections in their method calls, and you need to integrate those with your use of Scala collections.

Solution

Use the extension methods of the scala.jdk.CollectionConverters object in your Scala code to make the conversions work. For example, if you have a method named getNumbers in a public Java class named JavaCollections:

A Scala Factory Pattern example

Here’s a small example of how to create a Factory Pattern in Scala. In the Scala Cookbook I created what some people might call a simple factory and/or static factory, so the following code is a much better implementation of a true OOP Factory Pattern.

My Scala factory classes

I don’t have too much time to explain the code today, but here are the classes that make up my Scala factory, including a set of “animal” classes along with a DogFactory and CatFactory that extend an AnimalFactory trait:

Scala traits: Stackable modifications example in Scala

As a brief note today, here’s an example of stackable modifications using traits in Scala.

What is ‘super’ in Scala when you mix in traits?

I was curious about what super means when you mix Scala traits into a class or object. A simplified answer is that super refers to the last trait that’s mixed in, though I should be careful and note that this is an oversimplification.

You can demonstrate this in an example that uses both inheritance and mixins with traits. Given this combination of traits and classes:

An RxScala example

This is a little RxScala example from the RxScala/RxJava Github docs:

object Transforming extends App
{
    /**
     * Asynchronously calls 'customObservableNonBlocking'
     * and defines a chain of operators to apply to the 
     * callback sequence.
     */
    def simpleComposition()
    {
        AsyncObservable.customObservableNonBlocking()
            .drop(10)
            .take(5)
            .map(stringValue => stringValue + "_xform")
            .subscribe(s => println("onNext => " + s))
    }

    simpleComposition()
}

If you like visual diagrams, this source code goes along with this marble diagram.

I’ll be including examples like this in my book, Functional Programming, Simplified.

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.

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.

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.

How to get Java/Scala system environment variables and properties

Want to get the system environment variables and/or properties from your Scala or Java application? This quick post shows what environment variables and properties are available.

Here’s a little Scala application that prints all the environment variables and properties. You’ll see that you can convert it to Java very easily:

Scala: Print all environment variables and system properties

While working with the sbt and Mill build tools recently, and updating Scala and Java versions like crazy, I’ve been trying to verify some things in my Scala applications. Just now I wrote this little Scala 3 / Dotty application to print out all system environment variables and properties: