Short source code examples

When using Scala, if you ever need to list the subdirectories in a directory, or the files under a directory, I hope this example is helpful:

import java.io.File

object FileTests extends App {

    // list only the folders directly under this directory (does not recurse)
    val folders: Array[File] = (new File("/Users/al"))
        .listFiles
        .filter(_.isDirectory)  //isFile to find files
    folders.foreach(println)

}

If it helps to see it, a longer version of that solution looks like this:

As a quick note, here’s an example of how to use the Kotlin sortedWith syntax with an anonymous function (lambda). Given this list of integers:

val list = listOf(7,3,5,9,1,3)

Here’s an example of how to use sortedWith using a Comparator and lambda:

As a quick note, here’s an example of the Kotlin sortedBy syntax. Given this list of strings:

val names = listOf("kim", "julia", "jim", "hala")

the comments after these examples show how the Kotlin sortedBy function works:

Here’s a little Kotlin joinToString example. First, a sample list to work with:

val nums = listOf(1,2,3,4,5)

Then here’s the joinToString example:

nums.joinToString(
    separator = ", ",
    prefix = "[",
    postfix = "]",
    limit = 3,
    truncated = "there’s more ..."
)

When you put all of that code in the Kotlin REPL you’ll see this result:

Here’s a quick example of how to use the Kotlin groupBy syntax on a list, with the result of each example shown in the comments:

val names = listOf("kim", "julia", "jim", "hala")

names.groupBy { it -> it.length }  //LinkedHashMap: {3=[kim, jim], 5=[julia], 4=[hala]}
names.groupBy({it}, {it.length})   //LinkedHashMap: {kim=[3], julia=[5], jim=[3], hala=[4]}

If you need to see the data type (or class) of an instance in the Kotlin REPL, you can use the javaClass method to see that type. Here are a few examples:

Here’s a little Kotlin example that uses Java Swing, including a JFrame, JScrollPane, and JTextArea:

As a brief note, here’s some source code that I used to create a JMenuBar in a Java application. First, I defined some fields in my main class:

private static final KeyStroke fileOpenKeystroke = KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.META_MASK);
private Action fileOpenAction;
private JMenuBar menuBar;

Later in the same class I defined this method:

As a brief note to self, I use these Java keytool commands to add/update the SSL certificate for accessing a website named alphavantage.co:

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.

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

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

As a brief note to self, when you need to control spacing at the top of the title page (titlepage) in a LaTeX document, use the \vspace command, as shown in this example:

If you want to implement About, Preferences, and Quit handlers with Java 9 and newer on MacOS systems, this example Java source code shows how to do it:

As a quick Scala tip, if you haven’t worked with the flatMap on an Option much, it can help to know that flatMap’s function should return an Option, which you can see in this REPL example:

scala> Some(1).flatMap{ i => Option(i) }
res0: Option[Int] = Some(1)

You can tell this by looking at the function signature in the scaladoc for the flatMap method on the Option class:

Here’s an example of how to connect to a JDBC database with Scala. I have no idea why I got into the try/catch/finally details in a trivial little example like this, but if you want to see how to connect to a database with JDBC and query that database with a JDBC Statement (which yields a ResultSet), I hope this example is a little helpful:

Here’s another ScalikeJdbc example. The main benefits of this example are:

  • It shows how to perform a SQL SELECT with ScalikeJdbc
  • How to map the ResultSet values to create a series of objects from the ResultSet
  • How to connect to a database with ScalikeJdbc using a JDBC style of connecting (as opposed to putting the JDBC parameters in a configuration file)

Here’s the ScalikeJdbc example code:

Here’s an example of how to write a SQL UPDATE query with ScalikeJdbc:

def updateUrlClickGeoInfo(urlClickId: Long, gi: GeoInfo): Int = NamedDB('kbhr) localTx { implicit session =>
    sql"""
    update url_clicks
    set city = ${gi.city}, state = ${gi.state}, country = ${gi.country}
    where id = ${urlClickId}
    """.update.apply()
}

(As a note to self, this code comes from my PopulateKbhrGeo1 app.)

Here’s another Scala ScalikeJdbc SQL SELECT example. A few unique things about this example is that it shows the JDBC-style parameters; it shows how to use a case class and the “service” style approach; and it shows how to use the WrappedResultSet as shown. Here’s the code:

Here’s another ScalikeJdbc SQL SELECT example. If I remember right, this one doesn’t rely on a configuration file, it just uses the JDBC parameters shown:

Here’s another ScalikeJdbc SQL SELECT query example. In this example I use the concept of a “service,” which I probably originally got from the ScalikeJdbc website: