Posts in the “scala” category

A sample Scala/JavaFX application

As a brief note to self, here’s an example JavaFX application written using Scala 2:

package pizzastore

import javafx.application.Application
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.geometry.{Insets, Pos}
import javafx.scene.Scene
import javafx.scene.control.{Button, Label, Separator}
import javafx.scene.layout._
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.stage.Stage

object MainWindow {
    def main(args: Array[String]) {
        Application.launch(classOf[MainWindow], args: _*)
    }
}

class MainWindow extends Application  {
    override def start(stage: Stage) {
        val borderPane = new MainBorderPane
        val scene = new Scene(borderPane, 600, 400)
        scene.getStylesheets.add(getClass.getResource("pizza.css").toExternalForm)
        stage.setScene(scene)
        stage.setTitle("Al’s Pizza")
        stage.show
    }
}

class MainBorderPane extends BorderPane {

    // others need to be able to get this to add an action to it
    val placeOrderButton = new Button

    val alsPizzaLabel = new Label("Al’s Pizza")
    //label.setId("fancytext")   //css approach
    alsPizzaLabel.setFont(new Font("Arial", 50))
    alsPizzaLabel.setTextFill(Color.TOMATO)

    placeOrderButton.setText("Start An Order")
    placeOrderButton.setOnAction((e: ActionEvent) => {
        println("Hello World!")
    })
    placeOrderButton.setFont(new Font("Arial", 24))

    // a spacer to push the visible elements up a little
    val spacer = new Region
    spacer.setPrefHeight(40)

    val vbox = new VBox
    vbox.setSpacing(40)
    vbox.setAlignment(Pos.CENTER)
    vbox.getChildren.addAll(alsPizzaLabel, placeOrderButton, spacer)

    this.setCenter(vbox)

}

How to use variable names with the Scala ‘foldLeft’ method

Here’s a quick example of how to use variable names with the Scala foldLeft method:

val pSum = movies.foldLeft(0.0)((accum, element) => accum + p1Movies(element) * p2Movies(element))

In this example the variable movies is a Seq, and the variables p1Movies and p2Movies are Map objects.

The Scala String format approach (and Java String.format)

Scala String formatting FAQ: How do I write code that is equivalent to the Java String.format class? That is, how do I format strings like that in Scala?

NOTE: As of Scala 2.10 this approach is a little out of date. You can still use this approach, but there's a better way to handle this situation in Scala 2.10 and newer Scala version.

In Java I always write code like this to format a String:

How to define a default value for a method parameter that is a function

I was just reminded that functions are values just like Int, String, etc. Beyond the “typical” use cases, this is also true when it comes to supplying a default value for a function parameter that you’re passing into a method.

As some quick background, as I showed in the Scala Cookbook, you can define a method that provides default values for one or more of its parameters like this:

Creating a web browser with Scala Swing

Is Swing dead? I don’t know. I’ve written several Swing apps that I use every day, but I can’t speak for the rest of the world.

What I can say is that I really like Scala Swing. How I wish it was available ten years ago ... you’ll never know.

But getting to the point, after working with Scala Swing a little bit, I decided to see if I could write a web browser with it. The short answer is that here’s what the browser looks like:

Using Scala with Java Swing classes is pretty seamless

If you ever wanted to use Scala with Java Swing classes (like JFrame, JTextArea, JScrollPane, etc.), the process is pretty seamless. Here’s an example of a simple Scala/Swing application where I show a text area in a JFrame:

import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.JFrame
import javax.swing.JScrollPane
import javax.swing.JTextArea

object SwingExample extends App {

    val textArea = new JTextArea("Hello, Swing world")
    val scrollPane = new JScrollPane(textArea)

    val frame = new JFrame("Hello, Swing")
    frame.getContentPane.add(scrollPane, BorderLayout.CENTER)
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(new Dimension(600, 400))
    frame.setLocationRelativeTo(null)
    frame.setVisible(true)

}

Technically you’ll want to display the JFrame the way I show in How to create, center, and display a Java JFrame, but this code gives you an idea of how the process works.

I’ve written much larger applications with Scala and Swing, but for today I just wanted to share some code to show that it’s a very straightforward process.

How to sort a Scala Array

Scala FAQ: How do I sort the elements in an Array in Scala?

Solution: If you’re working with an Array that holds elements that have an implicit Ordering, you can sort the Array in place using the scala.util.Sorting.quickSort method. For example, because the String class has an implicit Ordering, it can be used with quickSort:

Scala: Standard style of using parentheses when calling procedures

As a brief note to self, when calling procedures in Scala, the Scala Style Guide suggests the following:

  1. If the procedure is basically just an accessor, leave the parentheses off
  2. If the procedure has some sort of side-effect, use the parentheses

These examples demonstrate the preferred procedure style:

val name = person.name   // a procedure that works like an accessor
openTheGarageDoors()     // a procedure that has a side-effect

Scala: How to create a list of alpha or alphanumeric characters

While looking for code on how to create a random string in Scala, I came across this article, which shows one approach for creating a random string. For my brain today, it also shows a nice way to create a list of alpha or alphanumeric characters.

For instance, to create a list of alphanumeric characters, use this approach:

val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')

To create a list of only alpha characters, just trim that code down to this:

val chars = ('a' to 'z') ++ ('A' to 'Z')

In the Scala REPL, you can see that this creates a Vector, which is a read-only, indexed sequence:

scala> val chars = ('a' to 'z') ++ ('A' to 'Z')
chars: scala.collection.immutable.IndexedSeq[Char] = Vector(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z)

Using the ++ operator (a method, actually) on Scala collections is a common way to merge/join/concatenate collections, and when I saw this code, I thought of what a great example it is of the ++ method.

It also shows that you can create a range of characters in Scala, which is something I didn't know you could do until recently. That's one of the things I love about Scala, it's a deep language, and I keep learning something new about it every day.

How to populate a Scala List with sample data (examples)

As a quick note, I was just reminded that you can populate a Scala List using a Range, like this:

scala> (1 to 5).toList
res0: List[Int] = List(1, 2, 3, 4, 5)

scala> (1 to 10 by 2).toList
res1: List[Int] = List(1, 3, 5, 7, 9)

scala> (5 to 11).toList
res2: List[Int] = List(5, 6, 7, 8, 9, 10, 11)

scala> ('d' to 'h').toList
res3: List[Char] = List(d, e, f, g, h)

Those are just a few examples. For many more ways to populate Scala lists with sample data, see How to populate Scala collections with a Range, How to generate random numbers, characters, and sequences in Scala, and Different ways to create and populate Lists in Scala.

How to create a range of characters as a Scala Array

I just noticed this quirk when trying to create an array of characters with the Scala Array.range method:

# works as expected
('a' to 'e').toArray              // Array[Char] = Array(a, b, c, d, e)

# surprise: Array.range always returns Array[Int]
val a = Array.range('a', 'e')     // Array[Int] = Array(97, 98, 99, 100)

I was surprised to see that the Scaladoc for the Array object states that the second example is expected behavior; Array.range always returns an Array[Int]. I suspect this has something to do with a Scala Array being backed by a Java array, but I didn’t dig into the source code to confirm this.

For much more information about arrays, see my Scala Array class examples tutorial.

Scala functions: Named arguments and default arguments

A nice feature of Scala is that in addition to letting you call and define functions just like you do in Java, you can also use both named arguments and default arguments. In this brief tutorial we'll look at both of these language features.

With Scala's named arguments (parameters), you can specify the names of function or method arguments when calling the method. Here's an example:

Scala: Importing Java classes and packages (import syntax, examples)

Summary: This brief tutorial shows Scala import statement syntax examples.

I was just trying to develop a little Java/Swing application in Scala, and right away I ran into the problem of how to import Java classes and packages into a Scala application. 

In short, the following code shows how to import a Java class into a Scala application:

Scala: Where are Coursier files stored on macOS?

Scala FAQ: Where are Coursier files stored on macOS?

Solution: The files Coursier downloads are located under this directory on macOS:

~/Library/Caches/Coursier

More specifically, in early 2021 they’re located under this directory:

~/Library/Caches/Coursier/v1

In a related note, this is my current JAVA_HOME, via Coursier:

/Users/al/Library/Caches/Coursier/jvm/adopt@1.11.0-9/Contents/Home

After a while this can be important to know, because the subdirectories can get quite large. Mine is currently over 4GB in size, and I’d like to delete some of that.

See the Coursier docs for more information.

Laminar 103: A small reactive routing example

In my first Laminar tutorial I showed how to set up a Scala/sbt project to use Laminar to render “static” HTML code. Then in Laminar 102: A reactive “Hello, world” example, I showed how to create a small, reactive Laminar example, that sends signals from one widget to another using observables and observers.

In my experience, the next thing you’ll need to know about Laminar is routing, i.e., how to transition from one page to another in a single-page app (SPA). Therefore, in this tutorial I’ll show how to implement that for very small applications.