Short source code examples

As a brief note to self, when you need to debug a chain of RxJava Observable method calls, you can use the doOnNext method to log the current values or print them to STDOUT or STDERR with println. Here’s an example from RxJava For Android Developers, where the debug output is logged with the Android Log.d method:

As a quick note today, if you need to configure an Android project to use Java 8, I found that adding this setting to the app-level build.gradle file worked:

compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

You can also use this syntax:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

That setting goes inside the android setting in the build.gradle file, as shown here:

If for some reason you ever need a list of people’s given names for testing your Java/Scala/Kotlin/JVM code, here’s a Java class with a sorted, static list of over 5,000 male and female given (first) names:

As a brief note to self, this is how I compiled/built an Android application (APK) from the MacOS command line and then ran it in an emulator. I include both my application- and system-specific notes, as well as the more generic commands I found at this Android.com URL:

When I tried to open an Android project with Android 3 that I probably created with Android Studio 2 and haven’t worked on in about two years, I got this error message:

As a brief note, here’s an example that shows how to create an RxJava 2 Observable from a Java List:

When you’re working with multi-threaded programming in Java — such as when working with Thread, Runnable, SwingUtilities.invokeLater, Akka, futures, or Observable in RxJava — you may need to get the name of the current thread as a way to debug your code. Here’s how you get the name of the current thread in Java:

I have no idea what I was thinking, but today I learned (or was reminded) that if you want the first element from a Scala Set you should use its head method, or headOption. For some reason I kept thinking that take should do the job, but you can see the results in the Scala REPL:

As a bit of warning, this is some old Java code, but if you want to create your own Java file utilities (utility methods), this code might help you get started:

I ran into a couple of interesting things today when trying to generate random alphanumeric strings in Scala, which can be summarized like this. I won’t get into the “random” stuff I was working on, but here are a couple of examples of how to generate lists of alphanumeric/ASCII characters in Scala:

scala> val chars = ('a' to 'Z').toList
chars: List[Char] = List()

scala> val chars = ('A' to 'z').toList
chars: List[Char] = 
List(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)

scala> val chars = (' ' to 'z').toList
chars: List[Char] = 
List( , !, ", #, $, %, &, ', (, ), *, +, 
     ,, -, ., /, 0, 1, 2, 3, 4, 5, 6, 7, 
     8, 9, :, ;, <, =, >, ?, @, 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)

As a brief note today, here’s a Scala method to generate a random string that is random length and also contains blank spaces:

If you ever need to intentionally throw and catch an exception with ScalaTest, here’s an example of how to do that:

As a little note to self, here are some examples of how to create ArrayList instances in Kotlin while explicitly assigning their types:

As a little note to self, here are a few let examples in Kotlin:

fun main(args: Array<String>) {

    fun toUpper(s: String?): String? = s?.toUpperCase()

    toUpper(null)?.let {
        // this will never be run
        println("toUpper(null) is: ${it}")
    }

    toUpper("emily")?.let {
        println("toUpper(emily) is: ${it}")
    }

    // `let` can return a value
    val hello = toUpper("Hannah")?.let {
        "Hello, ${it}"
    }
    println(hello)

}

The output looks like this:

As a short post today, here’s an example of a Kotlin implementation of the Adler-32 checksum algorithm:

I ended up not using this code, but if you wanted to see one way to use JSoup’s OutputSettings (Document.OutputSettings) class to set some parameters before calling JSoup.clean, I hope this is helpful:

// tried some things to improve the html output
val settings: OutputSettings = new OutputSettings
settings.prettyPrint(true)  //`true` is default
settings.charset("UTF-8")
settings.outline(true)  //this is close to what i want, but too extreme
settings.indentAmount(4)
val cleanHtml: String = Jsoup.clean(html, "", wl, settings)

I can attest that this code works, it’s just not what I need at the moment.

Also, the code shown is written in Scala, but as you can see, it converts easily to Java.

If you ever need a Scala method/function to convert a string with newline characters in it to a sequence of strings (Seq[String]), here you go:

def convertStringWithNewlinesToSeq(s: String): Seq[String] =
    s.split("\n").toVector

You can convert the final result to a Vector, Seq, List, ArrayBuffer, Array, etc., but I prefer Vector. The Scala REPL demonstrates how it works:

scala> convertStringWithNewlinesToSeq("")
res0: Seq[String] = Vector("")

scala> convertStringWithNewlinesToSeq("foo")
res1: Seq[String] = Vector(foo)

scala> convertStringWithNewlinesToSeq("foo\nbar\nbaz")
res2: Seq[String] = Vector(foo, bar, baz)

scala> convertStringWithNewlinesToSeq("foo\nbar\nbaz\n\n")
res3: Seq[String] = Vector(foo, bar, baz)

I’m short on time today, so I’ll just share this little example of how to write an implicit conversion function in Scala/Dotty:

Back in the old days I thought that any pattern that was including in single-quotes with the Unix grep command meant that the pattern inside the string was completely ignored by grep. But these days I have to escape special characters with a backslash character, which is really annoying. This example shows what I mean:

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