Posts in the “scala” category

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 cheatsheet

April, 2024 Update: This ZIO cheatsheet is currently being updated to ZIO 2.x, but it still needs a lot of work.

If you want a good cheat sheet right now, see this one on github. I’m creating my own as I learn ZIO and read the ZIOnomicon book. During the learning process I find that it’s much better to create your own by hand, that way you get something that’s meaningful to you.

Note that almost all of these initial examples come from the ZIOnomicon book and the video that I link to later.

ZIO HTTP: Netty AnnotatedNoRouteToHostException null solution

As a note to self, I had a problem with the ZIO HTTP library, where it was throwing Netty errors/exceptions like this:

io.netty.channel.AbstractChannel$AnnotatedNoRouteToHostException: null: jsonplaceholder.typicode.com.

The solution to this was to make a couple of changes to my SBT build.sbt file, specifically adding the javaOptions setting below, and forking the running application from SBT:

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

How to convert HTML to plain text with Jsoup (Scala and Java)

If you ever need to convert HTML to plain text using Scala or Java, I hope these Jsoup examples are helpful:

import org.jsoup.Jsoup
import org.jsoup.nodes.{Document, Element}

object JsoupHtmlToPlainTextTest extends App {

    val html =
        """
          |<html>
          |  <head><title>Hello, world</title></head>
          |  <body>
          |    <h1>Hello, world</h1>
          |    <p>Hello, world.</p>
          |    <p>This is a test.</p>
          |  </body>
          |</html>
        """.stripMargin

    // Example 1: this works, but all output is on one line
    val doc: Document = Jsoup.parse(html)
    //val s: String = doc.text()     //include <head> and <body> text
    val s: String = doc.body.text()  //<body> text only
    //println(s)

    // Example 2: this works, output is on multiple lines
    val formatter = new JsoupFormatter
    val plainText = formatter.getPlainText(doc)
    //println(plainText)

    // Example 3: this works as a way to select the <body> only
    val body: String = doc.select("body").first.text()
    //println(body)

    // Example 4: works: gets text from paragraphs only
    // https://jsoup.org/cookbook/input/parse-body-fragment
    val doc4 = Jsoup.parseBodyFragment(html)
    val body4 = doc4.body()
    val paragraphs = body4.getElementsByTag("p")
    import scala.collection.JavaConverters._
    val scalaParagraphs = asScalaBuffer(paragraphs)
    for (paragraph <- scalaParagraphs) {
        println(paragraph.text)
    }

}

While this is just some test code that I’m currently working on to understand Jsoup, the code shows four different ways to convert the given HTML into plain text. Hopefully the comments explain how the HTML to plain text conversion processes work, so I won’t write more about them. I just wanted to share this code snippet here today a) so I can find it again, and b) in hopes it might help others that need to convert HTML to text using Jsoup.

My free “Advanced Scala 3” video training course

March 24, 2024: I just released my free “Advanced Scala 3” online video training course. This free video course gets into different Scala programming topics such as functions, types, generics with variance and bounds, multiversal equality, modular programming, extension methods, and much more.

As always I want to thank Ziverge’s software consulting services for sponsoring these videos! These video courses take many weeks and even months to create, and they would not exist without Ziverge.

<<Click here to start my free Advanced Scala 3 video training course.>>

My free Scala and FP online video training courses

Welcome! This page contains direct links to all of the videos in my 100% Free Scala and FP Video Training Courses. When I say “100% Free”, I mean that there are no ads and no paywalls — all of the videos below are completely free to watch.

My first three courses are listed here, and when I add more free video courses I’ll update this page.

As always I want to thank Ziverge for making this possible! This videos take a long time to create, and I wouldn’t have the time to create these without Ziverge being a sponsor. If you ever want to thank the people at Ziverge, be sure to give them a call when your programming team needs assistance on programming projects. They work with Scala, Rust, A.I., Python, and much more.

Free functional programming book (free PDF for Scala, Java, Kotlin, etc.)

April, 2024: As a brief note today, the PDF version of my book, Learn Functional Programming The Fast Way!, is now FREE. I wrote this functional programming book for Scala, Java, and Kotlin developers, and you can now download it for free here:

If you’re interested in functional programming, or just want to learn more about data types, generics, pure functions, expression-oriented programming, and functional error handling, I hope this book is helpful.

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

Scala dates FAQ: How do I calculate the difference between two dates? That is, while using Scala — Scala 2 or 3 — you need to determine the difference between two dates.

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 SBT: How to “re-run with -deprecation” (or -feature)

Scala FAQ: When compiling a Scala application with SBT, I get warning messages like these:

$ sbt compile

[warn] there were 6 deprecation warnings; re-run with -deprecation for details
[warn] there were 4 feature warnings; re-run with -feature for details

How do I ’re-run with -deprecation’ or ’re-run with -feature’?

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