Posts in the “scala” category

Scala money and currency: The BigDecimal class and libraries

(Note: I don't have any immediate solutions in this article; it's more of a discussion of where I'm at today when looking at handling money/currency in Scala.)

As a quick note, I've started to look at handling money/currency in Scala, and I'm also starting to explore a couple of money/currency libraries.

A Scala shell script example (and discussion)

Scala shell script FAQ: How do I create a Unix/Linux shell script to run a small Scala script?

If you want to run a Scala script as a Unix or Linux shell script -- such as hello.sh -- write your script like this:

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, How to Parse Scala Strings Into Dates.

Problem

While using Scala (Scala 2 or 3), you need to parse a Scala String into one of the date/time types introduced in Java 8, and still used in Java 11, 14, 17, etc.

Scala Solution

If your String is already 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. The following examples demonstrate the expected formats, and other solutions.

How to iterate over Scala lists with foreach and for

Scala list/sequence FAQ: How do I iterate over a Scala List (or more generally, a Scala sequence) using the foreach method or for loop?

There are a number of ways to iterate over a Scala List using the foreach method — which is available to Scala sequences like List, Array, ArrayBuffer, Vector, Seq, etc. — and the for comprehension, and I'll show several of these solutions here.

How to add elements to a List in Scala (List, ListBuffer)

Scala List FAQ: How do I add elements to a Scala List?

Solution

"How do I add elements to a Scala List” is actually a bit of a trick question, because you can't add elements to a Scala List; it's an immutable data structure. If you’ve ever used the Java String type, it’s just like that, you can’t mutate its elements.

That being said, in the following sections I’ll show what you can do.

Prepending elements to Scala Lists

The most common way to “add” elements to a Scala List is to create a new List from an existing List by prepending elements to the existing list. We do this all the time in functional programming in Scala, and the general approach looks like this in the Scala REPL:

Scala: How to use startsWith tests in match/case expression

Scala FAQ: How can I use the startsWith method on a Scala String to match multiple possible patterns in a match expression?

Solution

As shown in the following example, you can use the startsWith method on a String to match multiple possible patterns in a match expression. startsWith checks to see if a String starts with the prefix (or substring) you specify, so although in these examples I use complete strings, you can also use regular expression patterns.

Example: startsWith + match expression

Scala/Java/Kotlin dates FAQ: How do I calculate the difference between two dates (LocalDate, ChronoUnit)

Scala date/time FAQ: How do I calculate the difference between two dates in Scala? That is, while using Scala 2 or Scala 3, you need to determine the difference between two dates. Also, you want to use the newest Java date/time API for this work, such as the date/time API in Java 8, 11, 14, 17, etc.

Solution: Calculating the difference between two dates (in Scala and Java)

If you need to determine the number of days between two dates in Scala — or Java or Kotlin — the DAYS enum constant of the java.time.temporal.ChronoUnit class provides the easiest solution:

Scala: How to concatenate two multiline strings into a resulting multiline string

I just had this problem in Scala where I wanted to concatenate two corresponding multiline strings into one final multiline string, such that the elements from the first string were always at the beginning of each line, and the lines from the second string were always second. (When I say corresponding, I mean that the two strings are of equal length.)

That is, given two Scala multiline strings like these:

Scala: How to use ‘fold’ on an Option (syntax, examples)

If you want to get a value out of a Scala Option type, there are a few ways to do it. In this article I’ll start by showing those approaches, and then discuss the approach of using the fold method on an Option (which I’ve seen discussed recently on Twitter).

1) Getting the value out of an Option, with a backup/default value

As a first look at getting values out of an Option, a common way to extract the value out of a Scala Option is with a match expression:

A Scala 3 function that counts the number of vowels in the String it is given as input

As a brief note today, here’s a Scala 3 function that counts the number of vowels in the String it is given as input:

def countVowels(s: String): Int =
    val vowels = Set('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    s.count(vowels.contains)

Note that this works because as I have mentioned in other places, a Scala Set can be used as a function — specifically as a predicate — and the count function on the Scala sequence classes expects a predicate.

Scala 2 solution

A Scala function to get the Unix epoch time for X days ago

As a brief note today, here’s a Scala function to get the Unix epoch time for X days ago (5 days ago, 10 days ago, etc.):

/**
 * Returns a 10-digit Long (like 1585275929) representing the date/time.
 * Use it to get the time for 1 day ago, 2 days ago, etc. `0` will give
 * you the current time.
 */
def unixEpochTimeForNumberOfDaysAgo(numDaysAgo: Int): Long = {
    import java.time._
    val numDaysAgoDateTime: LocalDateTime = LocalDateTime.now().minusDays(numDaysAgo)
    val zdt: ZonedDateTime = numDaysAgoDateTime.atZone(ZoneId.of("America/Denver"))
    val numDaysAgoDateTimeInMillis = zdt.toInstant.toEpochMilli
    val unixEpochTime = numDaysAgoDateTimeInMillis / 1000L
    unixEpochTime
}

As shown in the comments, if you give it a 0 it will return the current epoch time. As shown by the function’s type signature, the function’s return type is a Long (which is a 64-bit two's complement integer).

Of course you can make the code shorter and better; I just wanted to show the steps in the approach using the Date/Time classes that were introduced in Java 8.