Posts in the “scala” category

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:

A ZIO JSON solution to parse/decode JSON with blank spaces in the keys (and a type hierarchy)

As a brief note today, I was starting to look at a free JSON REST web service that to get stock information, and their JSON for a single stock looks like this:

{
    "Global Quote": {
        "01. symbol": "IBM",
        "02. open": "182.4300",
        "03. high": "182.8000",
        "04. low": "180.5700",
        "05. price": "181.5800",
        "06. volume": "3037990",
        "07. latest trading day": "2024-04-19",
        "08. previous close": "181.4700",
        "09. change": "0.1100",
        "10. change percent": "0.0606%"
    }
}

A ZIO 2 collectAllPar example using Scala 3

As a brief note today, if you want to see an example of the ZIO collectAllPar method, the Scala 3 source code below shows one possible example that uses collectAllPar in a for expression.

First, here’s a small snippet of code that shows just the key parts:

ZIO 2: Solution to "ZIO.cond not working" (code not running)

I just wrote the following ZIO 2 question about how to use ZIO.cond to a friend, and got the answer shown. I’ve also added in my own comments where they make sense.

ZIO.done question

Hey, I’m trying to understand why my ZIO failWithMsgEffect doesn’t seem to get run in the following code example?

I have learned that there are better ways to handle this, but I’ve found that if I don’t understand something like this, it will come back to bite me later. Here’s the code:

ZIO 2: A ZIO.timeout interrupt example with ZIO.attempt

As a little ZIO 2 example with Scala 3, here’s some code that starts to show how to use ZIO.timeout along with ZIO.attempt while accessing an internet URL with Scala’s Source.fromURL.

Basically all I’m doing is:

  • I attempt to access a URL using Scala’s Source.fromURL,
  • and then I add a timeout to that, specifically a ZIO##timeout

Here’s the code:

Scala FAQ: How Do I Create New Date and Time Instances with Scala

Scala date/time FAQ: How do I create new date and time instances with Scala? Specifically, using Scala, how do I create new date and time instances using the Date and Time API that was introduced with Java 8.

Solution: Creating dates and times in Scala (Java and Kotlin, too)

Using the Java 8 API and newer — Java 11, 14, 17, etc. — you can create new dates, times, and date/time values. The table below provides a description of some of the new Java date/time classes you’ll use (from the java.time Javadoc), all of which work in the ISO-8601 calendar system.

How to left-trim and right-trim strings in Scala

As a brief note, here are a few examples of how to implement left-trim and right-trim on strings in Scala:

def ltrim(s: String) = s.replaceAll("^\\s+", "")
def rtrim(s: String) = s.replaceAll("\\s+$", "")

If I ever write a Scala StringUtils class, I’ll be sure to include those functions in that class.

Scala: How to execute (exec) external system commands

Scala exec FAQ: How do I execute external system commands in Scala?

When it comes to executing external system commands, Scala is a dramatic improvement over Java. The operators Scala makes available are much more like Perl or Ruby, and the operators themselves are consistent with traditional shell commands, and are therefore easy to remember. Let's take a look at a few examples.

Scala/Java/Kotlin: How to replace left and right brackets in a String (replaceFirst, replaceAll)

Scala/Java/Kotlin String FAQ: How do I replace left brackets and right brackets — i.e., the [ and ] characters — in a String when using methods like replaceFirst and replaceAll?

Solution

If you’re using Scala, Java, Kotlin, or other JVM languages, and need to replace left or right brackets in a String, I found the following solution, which seems to work well with String methods like replaceFirst and replaceAll.

Scala 3 ‘while’ loop syntax and examples

As a brief note today, here are several examples of the Scala 3 while loop syntax.

Scala 3 while/do syntax

First, here are some one-line examples. This is the preferred syntax, using the while/do keywords.

while i >= 0 do i = f(i)