Short source code examples

I just started using a new version of SBT, and when I went to run a test I got this SBT warning message:

At the moment this is kind of funky, but I find that the best way to determine the version of SBT is to move to a temporary directory and then run the sbt sbtVersion command:

As a quick note to self, here’s an example of how to set scalacOptions in an SBT build.sbt file:

scalacOptions ++= Seq(
    "-Xfatal-warnings",
    "-deprecation",
    "-feature",
    "-unchecked",
    "-language:implicitConversions",
    "-language:higherKinds",
    "-language:existentials",
    "-language:postfixOps"
)

As shown, scalacOptions lets you set Scala compiler options in your SBT project build.

If you ever need to convert HTML to AsciiDoc, I just used this Pandoc command and it seems to work well:

pandoc --wrap=none -f html -t asciidoc myfile.html > myfile.adoc

The wrapping part of that command isn’t 100% necessary, but if you don’t use it, Pandoc will wrap the plain paragraph text, which I don’t like because I’ll be editing the resulting AsciiDoc text.

Here’s some of the AsciiDoc text that this command generated:

As a brief note to self, if you need to convert an Asciidoc file named test1.adoc to HTML format, this command works:

asciidoc -o test1.html test1.adoc

Of course a key here is that you need the asciidoc command installed. I installed it on my Mac with Homebrew, something like brew install asciidoc.

(It may also be possible to do this conversion with Pandoc, but I didn’t have any initial success with it.)

 

As a brief note to self, here’s an early example of the syntax of Intersection Types in Scala 3 (Dotty):

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: