Posts in the “scala” category

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.

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?

[toc]

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")
bw.close

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

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

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(
    FileWriter(
        File("/tmp/file.out"),
        true
    )
)

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

A sample .gitignore file for Scala/SBT projects

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

# bloop and metals
.bloop
.bsp

# metals
project/metals.sbt
.metals

# vs code
.vscode

# scala 3
.tasty

# sbt
project/project/
project/target/
target/

# eclipse
build/
.classpath
.project
.settings
.worksheet
bin/
.cache

# intellij idea
*.log
*.iml
*.ipr
*.iws
.idea

# mac
.DS_Store

# other?
.history
.scala_dependencies
.cache-main

#general
*.class

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:

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.