Posts in the “scala” category

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.


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.


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 trait examples and syntax

This page contains a collection of Scala trait examples. I created many of these examples when I was writing the Scala Cookbook. Unlike the Cookbook, where I explain these examples in great detail, on this page I’m just sharing many of the examples so you can use this as a trait reference page. (The Cookbook actually contains more examples than this page.)

Without any more introduction, here are the examples.

[toc hidden:1]

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:

Scala 3 Unions: Simulating Dynamic Typing with Union Types

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 23.9, Simulating Dynamic Typing with Union Types.


You have a situation where it would be helpful if a value could represent one of several different types, without requiring those types to be part of a class hierarchy. Because the types aren’t part of a class hierarchy, you’re essentially declaring them in a dynamic way, even though Scala is a statically-typed language.


In Scala 3, a union type is a value that can be one of several different types. Union types can be used in several ways.

In one use, union types let us write functions where a parameter can potentially be one of several different types. For example, this function, which implements the Perl definition of true and false, takes a parameter that can be either an Int or a String:

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.


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


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.


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


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.

A Scala current date and time example

Scala date/time FAQ: How do I get the current date and time in Scala?

Getting the current time

The following code demonstrates how to get the current time in Scala, and then further shows how to get other information, such as the current minute, using the Java SimpleDateFormat class:

[toc hidden:1]

Scala tuple examples and syntax

Scala FAQ: Can you share some examples of using tuples in Scala?

A Scala tuple is a class that can contain a miscellaneous collection of elements. I like to think of them as a little bag or container you can use to hold things and pass them around.

You create a tuple with the following syntax, enclosing its elements in parentheses. Here's a tuple that contains an Int and a String:

[toc hidden:1]

Scala: What do “effect” and “effectful” mean in functional programming?


When you get started with functional programming (FP) a common question you’ll have is, “What is an effect in functional programming?” You’ll hear advanced FPers use the words effects and effectful, but it can be hard to find a definition of what these terms mean.

Effects are related to monads (but don’t worry)

A first step in the process of understanding effects is to say that they’re related to monads, so you have to know a wee bit about monads to understand effects.

As I wrote in my book, Functional Programming, Simplified, a slight simplification is to say that in Scala, a monad is any class that implements the map and flatMap methods. Because of the way Scala for-expressions work, implementing those two methods lets instances of that class be chained together in for-expressions (i.e., for/yield expressions).

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

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))
bw.write("Hello, world\n")

FileWriter takes two arguments, so this might be a little easier to read:

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

Scala 3

While I’m in the neighborhood, 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(

Scala zip and zipWithIndex examples (with Stream)

I’ve known about using Scala’s zipWithIndex method for quite some time. I used it in for loops to replace counters, and it works like this:

scala> List("a", "b", "c").zipWithIndex
res0: List[(String, Int)] = List((a,0), (b,1), (c,2))

I learned about using zip with Stream last night while reading Joshua Suereth’s book, Scala In Depth. It works like this:

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).

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()
            .map(stringValue => stringValue + "_xform")
            .subscribe(s => println("onNext => " + s))


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.

A sample .gitignore file for Scala/SBT projects

This is a sample .gitignore file that I use for Scala SBT projects:

# bloop and metals

# metals

# vs code

# scala 3

# sbt

# eclipse

# intellij idea

# mac

# other?


I’ll update this file over time, but for now I just want to put an example gitignore file out here so I don’t have to try to remember which gitignore file I created last.

One final note: Some of those files/directories are unique to SBT, some are for IntelliJ IDEA, others are for Scala/Eclipse, and .DS_Store is Mac-specific. Use whatever you want/need.

Some of this is counter to recommendations, so buyer beware. More info: