Posts in the “scala” category

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.

Scala, JSoup, HTML, CSS selectors, and a Sparkline chart

As a brief note today, here’s a little Scala application that reads an HTML file, parses it with JSoup, and then I select all of the elements with the CSS selector shown. After that, I use some Scala goodness to read all the text values of those elements, see if there is a "W" (win) or "L" (loss) character there, convert that to a Seq[Boolean], and then generated an ASCII Sparkline chart based on those results.

Note that the desired CSS selectors look like this in the HTML:

Neotype as a better solution than Scala 3 opaque types

As I mentioned previously, the Neotype library is a nice improvement over the verbose Scala 3 opaque type feature. This little example begins to show how much better Neotype is than opaque types, where opaque types require more boilerplate to implement less functionality:

//> using scala "3"
//> using lib "io.github.kitlangton::neotype::0.3.0"

import neotype.*

// [1] Opaque type:
opaque type Username = String
object Username:
    def apply(value: String): Username = value

// [2] Neotype:
object Password extends Newtype[String]:
    override inline def validate(input: String): Boolean =
        input.nonEmpty && input.length > 2

@main def NeotypeTests =

    val u = Username("Alvin")
    println(u)
    
    val p = Password("12")
    println(p)

Scala: How to use Iterator.continually to loop over a ResultSet iterator (and handling iterating in a functional way to create a list)

Sometimes when you’re working with Scala and want to do things in a functional way, the solution isn’t always clear. For instance, I wanted to write a database query using plain old SQL and JDBC, so to do that, I needed to work with iterating over a ResultSet.

Specifically, I’m writing a little “password manager” application, and for one function I just wanted to return list of all the “app names” stored in the database, where an “app” is something like Gmail, Facebook, Twitter, or any other application or service that requires a username and password.

Scala, functional programming, and working with an iterator

Some Scala Exception ‘allCatch’ examples (Option, Try, and Either shortcuts)

At the time of this writing there aren’t many examples of the Scala Exception object allCatch method to be found, so I thought I’d share some examples here.

In each example I first show the "success" case, and then show the "failure" case. Other than that, I won’t explain these, but hopefully seeing them in the REPL will be enough to get you pointed in the right direction: