Short source code examples

As a brief note to self, I was just converting some Java code to Kotlin, and the correct way to convert this Java for loop that uses i as a counter:

for (int i=0; i<tabLayout.tabCount; i++) { ...

is with this Kotlin for loop:

for (i in 0 until tabLayout.tabCount) { ...

The key there for me is the 0 until part of the syntax.

As a note to self, here’s an example of implementing a FragmentStatePagerAdapter Android class in Kotlin:

As a quick note to self, this is an example of how to implement a setOnClickListener on a FloatingActionButton with Android and Kotlin:

fab.setOnClickListener { view ->
    Snackbar.make(
        view,
        "An exciting message!",
        Snackbar.LENGTH_LONG
    ).setAction("Action", null).show()
}

Hopefully that’s enough to get “future me” pointed in the right direction when I need this again. :)

(There are more lambda details at this link.)

If you need to generate a small random number in Kotlin, I find that this approach works:

val r = (1..10).shuffled().first()

That code generates a single random number in the range from 1 to 10 (including 1 on the low end and 10 on the high end).

You can use the technique to simulate the rolling of a dice (die):

val r = (1..6).shuffled().first()

Or simulate flipping a coin (0=heads, 1=tails, or vice versa):

val r = (1..2).shuffled().first()

This also works for the coin flip simulation:

It’s a little hard to move back and forth between Scala and Kotlin because of some of the differences between the languages. Skipping the long story, here’s an example of how to print every line in a list of strings in Kotlin using forEach and println. First the setup:

import java.io.File
fun readFile(filename: String): List<String> = File(filename).readLines()
val lines = readFile("/etc/passwd")

Then here are two different ways to use forEach with println:

If you need to convert an array of bytes to a hex string in Scala, I can confirm that this code works:

def convertBytesToHex(bytes: Seq[Byte]): String = {
    val sb = new StringBuilder
    for (b <- bytes) {
        sb.append(String.format("%02x", Byte.box(b)))
    }
    sb.toString
}

I just used this code as part of a checksum algorithm (SHA-1, SHA-256, etc.), and I tested it against command line checksum commands to verify that it works properly.

If you ever need to create and populate a Kotlin list, I can confirm that these approaches work for an immutable and mutable lists:

// fill an immutable list
val doubles = List(5) { i -> i * 2 }

// fill a mutable list of ten elements with zeros
val ints = MutableList(10) { 0 }

The Kotlin REPL shows how these approaches work:

As a quick note today, here’s an example Play Framework Anorm SQL SELECT query that queries for a single value:

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: