Posts in the “scala” category

Scala: An ASCII “current value in range” chart/plot (Sparkline)

I just wrote some Scala code to create an ASCII chart/plot that looks like this:

+-------------------------|-------------------------+
                 ^

In this chart, the left side of the chart represents a low value, the right side represents a high value, so the overall line represents that range, and then the ^ on the second line indicates the current value. This can be used to show the 52-week low and high values for a stock, along with its current range. It could also be used to show someone’s current batting average in a season, compared to their low and high values, and any other value that can be expressed as low, high, and current values.

I initially thought the correct name for this was a Sparkline chart, but it’s really something like a “current value in range” chart. I haven’t been able to find the exact correct name, but that’s close enough for now.

Scala: Examples of for-expressions being converted to map and flatMap

Without any explanation, here are a couple of source code examples from my book, Learning Functional Programming in Scala. The only thing I’ll say about this code is that I created it in the process of writing that book, and the examples show how the Scala compiler translates for-expressions into map and flatMap calls behind the scenes.

ZIO: How a ZIO value looks like a blueprint in the Scala REPL

A nice thing about using ZIO in the Scala REPL is that it really demonstrates the whole “blueprint” concept. As shown in the example below, after I create the username variable, the REPL shows that username is basically just a data structure. Nothing happens at this time other than the creation of that data structure, which can be executed at a later time.

Getting a random element from a list of elements in Scala

In working on projects like SARAH and other apps where I try to make a computer seem more “human,” I’ve been making my software reply to me in random ways. What I’ve found is that this ends up being an easily repeatable pattern, where you have a list of possible replies, and then you randomly return one of those replies.

Scala Either type: How to get the value out of an Either

Scala Either FAQ: How do I get the value out of a Scala Either?

Solution

In this recipe I show many different ways to get the value out of a Scala Either, while accounting for the fact that an Either value may be a success value (a Right) or a failure value (a Left).

Scala: How to download URL contents to a String or file

Scala URL FAQ: How do I download the contents of a URL to a String or file in Scala?

I ran a few tests last night in the Scala REPL to see if I could think of different ways to download the contents of a URL to a String or file in Scala, and came up with a couple of different solutions, which I'll share here.

Download URL contents to a String in Scala

The best way I could think of to download the contents of a URL to a String looks like this:

Scala and the two kinds of programming languages

I know that it’s fashionable to say that Scala is dead or something similar to that, but I’ve gotten a few royalty checks from O’Reilly this year for the Scala Cookbook that are amazingly good (💰) for a 3-year old programming book.

Shoot, I’d be happy to receive these royalty payments during the initial months after the book’s release.

As Bjarne Stroustrup said, “There are only two kinds of programming languages: the ones people complain about and the ones nobody uses.”

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:

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:

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.