Posts in the “scala” category

ScalaTest 102: Writing TDD style unit tests with ScalaTest

Problem: You want to use test-driven development (TDD) style tests in your Scala applications, and need to see examples of how to write them.

Solution

Have your test classes extend the ScalaTest FunSuite, and then write your tests. Because most tests involve a setup and teardown process, you’ll usually also want to add in the BeforeAndAfter trait as well.

ScalaTest 112: How to run ScalaTest unit tests in Eclipse

Problem: How do I use ScalaTest in Eclipse (or, How do I run my ScalaTest unit tests from Eclipse?)

Solution

I do a lot of work from the command line with Ant builds and similar things, but there are times I like to do things through Eclipse. Today I wanted to run my ScalaTest unit tests in Eclipse, and found this to be a straightforward task.

Besides Scala, Eclipse, and an Eclipse project, you'll need:

On the Scala Future, and semantics

In programming, semantics can be important. While in many cases I don’t care too much how developers name classes and variables, in some cases monikers can cause problems. (Perhaps even in that sentence.)

Scala equivalent of Java .class (classOf)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is one of the shorter recipes, Recipe 6.2, “The Scala equivalent of Java’s .class.”

Problem

When an API requires that you pass in a Class, you’d call .class on an object in Java, but that doesn’t work in Scala.

Using `puts` or `echo` instead of `println` in Scala

As my mind was wandering off earlier today, I started to wonder what it would take to create a Ruby puts or PHP echo statement in Scala. (For some reason my brain can never type “println,” and puts or echo are much easier to type.)

One simple way to mimic a puts or echo method is to use Scala's ability to rename things on import:

scala> import System.out.{println => echo}
import System.out.{println=>echo}

scala> import System.out.{println => puts}
import System.out.{println=>puts}

scala> echo("foo")
foo

scala> puts("foo")
foo

scala> puts(1 + 1)
2

An “sbt new” shell script (that removes the project and target directories)

As a quick note, I wrote this little Unix/Linux shell script that I named sbtnew to run the sbt new command (with the template shown), and then delete the project and target directories that sbt new creates in my current directory:

#!/bin/sh

# sbtnew:  a script to run 'sbt new' and then clean up the project and target directories
# version: 0.1
# license: GNU GENERAL PUBLIC LICENSE, see https://choosealicense.com/licenses/gpl-3.0/#

# [1] create a new Scala 3 project
sbt new scala/scala3.g8

# [2] clean up the 'project' and 'target' directories
if [ -e project ]
then
    echo "i see project"
    rm -rf project
fi

if [ -e target ]
then
    echo "i see target"
    rm -rf target
fi

Please note that this project/target directory situation seems to be getting better with new versions of sbt, so this sbtnew shell script may not be needed in the future, but I still like it because it’s easier to remember than the full sbt new... command. One day I’ll also add the ability to rename the directory to what I entered, because for some reason sbt new changes the name to lowercase.

Automated GUI Testing (AGT) software, version 0.1.0

As I noted here on the Valley Programming website, I just released Version 0.1 of my Automated GUI Testing (AGT) software. It still needs a lot of work, but a key is that I added in some basic image-recognition capability. This means that as a GUI tester, you don’t have to rely on pixel coordinates; you can instead write, “Find this icon on the screen, and when it’s visible, click it.” Similarly, you can also write, “When this given icon goes away, do (whatever you need to do).”

I’ll write more about AGT over time, but for today, I’m happy to get to Version 0.1.

Scala 3: How to create and run a Scala script

As a brief tip today, in Scala 3 you can run a script as follows. First, put this Scala 3 code into a file named Hello.scala:

@main def hello = println("Hello, world")

Next, at your operating system command line, run your script like this:

$ scala Hello.scala
Hello, world

For a little script with no dependencies, that’s all you need to do.

Putting a JAR file on the classpath with your script

If you happen to need a JAR file when running your Scala 3 script, you can run it like this:

scala -cp MyNecessaryJarFile.jar Test.scala

Here in October, 2021, I just confirmed that this works as desired.

An intentionally slow Scala 3 HTTP server

For a variety of reasons I recently wrote an “intentionally slow” HTTP socket server using Scala 3. Though I also wanted to test some things with Scala 3, the main reason for writing it is so I can test some client-side code, and make sure I handle server-side timeouts correctly.

Scala build.sbt GraalVM native-image command line options

As a quick note to self, I just used these contents in a Scala/sbt build.sbt file when working with the GraalVM native-image command (and sbt plugin). I share these here so I can remember how to specify command-line options for the native-image plugin in the build.sbt file:

lazy val sbtmkdirs = (project in file("."))
    .enablePlugins(NativeImagePlugin)
    .settings(
        name := "http_client",
        version := "0.1",
        scalaVersion := "3.0.1",
        Compile / mainClass := Some("foo.HttpClient"),
        // these are the native-image options i used
        // to work with HTTP and HTTPS (though I don’t know
        // if they are all needed)
        nativeImageOptions ++=
            Seq(
                "-H:EnableURLProtocols=http",
                "-H:EnableURLProtocols=https",
                "--enable-url-protocols=http,https",
                "--enable-https",
                "--enable-http"
            )
    )

scalacOptions ++= Seq(
    "-deprecation",
    "-explain",
    "-explain-types",
    "-new-syntax",
    "-unchecked",
    "-Xfatal-warnings",
    "-Xmigration"
)

It’s also helpful to see that sbt/build.sbt Compile / mainClass syntax, because that’s currently hard to find on the internet

Learning how to write a technology book (for O'Reilly)

A fun part of writing the Scala Cookbook has been learning more about the process of thorough writing, and doing more research about topics than I’ve ever done before.

The process goes something like this: For the next 24 hours I'm working on editing the “XML & XPath” chapter, which was originally written a few months ago. For these 24 hours, I let myself “love” processing XML with Scala.

I try all sorts of experiments with Scala/XML code, and read dozens (maybe hundreds) of web pages about problems developers are having, and potential solutions. During this time I try not to leave any stone unturned, and if one clue leads to another, well, I just keep following them, trying to find the “best” way(s) to solve each problem, hoping to add one or two extra nuggets that will make an important difference to readers of this chapter.

Tomorrow, and the next day

Then another interesting thing happens: Tomorrow I forget all about XML, and “love” SBT. I do all that research and perform all those experiments on SBT, again trying to leave no stone unturned.

Then the next day I forget about SBT and “love” some other piece of Scala technology.

For each chapter, I think to myself that I want a developer in a bookstore to pick up the Scala Cookbook, thumb through that chapter, and think, “Man, this chapter alone is worth the price of the book.” Frankly, I don't know if I'm there yet on all the chapters, but it's getting close.

A note here on the “love” part: Like everyone else, I have a lot of other things going on in life, and I find it helps if I “give myself permission” to spend all this time on one subject (and all this time on a book I hoped to have completed in December or January).

Writing for O'Reilly

To their credit, the folks at O'Reilly have been very patient with me. Whenever I think too much time has passed, they tell me to take my time and write a great book, everything else will take care of itself.

Being a first-time author, I originally wanted to have the book released around the New Years holiday (when people had extra money, or were spending it more freely), but looking back at the manuscript I submitted back in November, I have to agree, it was crap. The problems and solutions were okay, but there was no depth to them. I'm much happier with what I have now.

Writing these recipes is different than writing a blog post on this website. When I write a post here, it usually reflects a problem I've just run into, and how I solved it. The book is much deeper than that, and among other things, shows alternate approaches, better examples, and more research behind the problem/solution.

Also, although we've had some delays because of issues with reviewers, the review process itself has been incredibly helpful. The best reviewers have pointed out my errors, suggested alternate approaches, and provided better examples.

Working from home

Working from home has also been interesting. I've worked from home for several years now, but lately it has gotten boring, and I long for the company of working with others, as part of a team. This has made me more distracted than I was a few years ago.

To fight my feelings of distraction, I've recently started the mornings like this:

First, I work a little on this website to get my brain going.

Next, I work in 20-30 minute increments, like this:

  1. Work for 20-30 minutes.
  2. Take a short break, wash the dishes, clean a little, check social media, whatever.
  3. Work for 20-30 minutes.
  4. Take a short break.

I continue that cycle until I really get into the work, at which time the breaks seem more annoying than helpful. At this point I usually work several consecutive hours without break.

To enforce the cycle, I set a timer on the microwave in the kitchen. Although I wrote a timer application long ago that I use when meditating, I find that using the microwave timer is better because it forces me to get up.

(On my really bad days I find that it's useful to count how many twenty minute work segments I've managed. To do this, I make a series of tick marks on a piece of scrap paper. Twelve tick marks equates to four hours of real work, and on those days, I try to be happy with that.)

The other thing I do is print the chapters and take them to a coffee shop so I can review them there. I could edit them on my laptop, but for me, it's nice not to look at a computer screen for a while.

Summary

My degree is in Aerospace Engineering, and the thing I thought was best about college is that I “learned how to learn”. With this book, I feel like I've learned a lot about the process of writing a technology book. For my personality, the biggest thing has been giving myself permission to indulge myself in each topic, and then make it the best I can.

The Play Framework template comments syntax

When you want to create Play Framework template comments, use the @* ... *@ syntax.

Single line Play Framework comment

Here's a one-line Play Framework comment:

@* COMMENT *@

Multi-line Play comment

Here's a multi-line Play comment:

@*
 * Four score
 * and seven year ago
 * our fathers ...
 *@

Scala 3: How to search the Scaladoc with function signatures

A great new feature in the Scala 3 Scaladoc is that you can search for methods by supplying a method/function signature. For instance, imagine that you’re new to Scala, and you have this list:

List("Ken", "Frank", "Lori")   // A

Furthermore, you know that you want to get to this list, which contains the length of each string in the first list:

List(3, 5, 4)                  // B

Scala 'map' method: examples and syntax (List, Vector, Seq)

As a quick note today, in this post I’ll share some examples of the Scala map method as it works on sequences like the List, Vector, and Seq classes.

map == transform

Basically you can think of map as meaning transform: it lets you transform one collection into another. For instance, these examples in the Scala REPL show how to transform a list of strings into a list of integers, where the integers correspond to the length of each string:

What makes Scala special

While at a doctor’s office, a nurse asked me what makes Scala special.

I said, “You know how some spoken languages sound beautiful, like Italian or French? In the same way, some programming languages look beautiful, like Scala 3. So we use other languages when we’re forced to, but we use beautiful languages because we want to.”