Posts in the “scala” category

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.

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

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.