Posts in the “scala” category

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:

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:

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%"
    }
}

ZIO ZLayer: A simple “Hello, world” example (dependency injection, services)

As a brief note today, here is some source code for a ZIO ZLayer application using Scala 3. In this code I use the ZLayer framework to handle some dependency injection for a small application. (Note that I don’t like to use the word “simple” when writing about software, but I have tried to make this as simple as I can.)

I’ve commented the code below as multiple “parts” so you can see the thought process of creating an application that uses ZLayer. Basically the idea is that your application needs some sort of service — which might be like a database connection pool, HTTP framework, etc. — and then you make that service available to your application with ZLayer’s provideLayer function (or one of its other functions).

The ZLayer example

Given that small introduction, here’s my ZIO ZLayer example, with many notes shown in the comments inside the code:

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:

ZIO 2 Example: Making an HTTP GET request with a timeout, using sttp client

As a brief note today, here’s an example of making an HTTP GET request using ZIO 2 and the Scala sttp library. I also let the user specify a “timeout” value, so the request will timeout, rather than hanging.

As a very important note, this is a blocking approach, not a non-blocking approach.

Here’s the source code and Scala 3 + ZIO 2 + sttp function:

ZIO 2 Example: Print values after a random delay (and the ZIO error channel)

As a brief note today, here’s a little ZIO 2 example that shows how to print a series of values with a random delay in between each value that’s printed.

Note that there are different ways to implement randomWaitTimeInSeconds ... for instance, it could return a Duration, but I just have it return an Int.

I also use ZIO.foreach to generate the values in a range, and that could be handled differently.

Another thing I do is use an exception inside ZIO.fail, and I do that because I want that error to be a Throwable on the ZIO “error channel” (i.e., the E parameter in ZIO[R, E, A].)

ZIO.attempt: examples and documentation

ZIO 2 FAQ: How do I work with the ZIO.attempt function?

Solution

When you’re working with existing (legacy) Scala code that:

  • is synchronous, and
  • can throw an exception

wrap that code with ZIO.attempt. As you’re about to see, this creates a ZIO effect from that legacy code.

Not only does this create a ZIO effect, it also puts the exception in the ZIO “error channel,” i.e., the E parameter in the ZIO[R, E, A] type signature.

ZIO/ZLayer FAQ: How to use a Java Properties files with ZIO

ZIO/ZLayer FAQ: How do I use a Java Properties file with ZIO 2 and Scala?

Solution

You can use the zio-config library for things like this, but at the moment my preferred approach is to hand-code this ZLayer solution. Maybe that’s because I know how to work with a Java Properties file, i.e., how to read and load it, so I like to see those details.

Therefore, given this Java properties file named application.properties:

ZIO/ZLayer FAQ: How do I create a very simple ZLayer with ZIO 2?

ZIO FAQ: How do I create a very simple ZLayer in a ZIO 2 application?

Solution

As a wee bit of background, the ZIO Zlayer approach provides several important purposes, including:

  • Dependency injection
  • Modularity and composability
  • Resource management
  • Testability
  • Separation of concerns
  • Type safety

At its most basic, the ZIO 2 ZLayer gives you a way to provide configuration information to your application, similar to dependency injection approaches with other languages and tools.

A simple ZLayer example

For instance, imagine that your application requires configuration information such as (a) SQLite database configuration information and (b) an email address. One way to start solving this problem is to define a Scala case class for each piece of configuration information:

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.

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.