Posts in the “scala” category

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.

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:

Scala CLI (Compiling and Running Code)

I initially created this “How to use Scala CLI” content for my new Scala book, Learn Functional Programming Without Fear, but when I decided to shorten what I include in the book, I also decided to put the full version of this content here.

What is Scala CLI?

Until some time in the year 2021 I would have written this book using only the Scala SDK and its scalac and scala commands to compile and run your code, respectively. (These are just like javac in Java, kotlinc in Kotlin, and java with both of those.)

But since that time the Scala CLI command project has come along, and it greatly simplifies the “getting started with Scala” experience, so I use it in this book. Scala CLI:

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.

Scala 3 dates: How to parse strings into dates (LocalDate, DateTimeFormatter)

[toc]

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.

Scala: How to square a number (Int, Double, Float, Long)

Scala math FAQ: How do I square a number in Scala, such as squaring an Int, Double, Long, or Float?

Solution

You can square a number in Scala in at least two different ways:

  1. Multiply the number by itself
  2. Call the Java Math.pow function or the scala.math.pow function

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:

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:

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.>>