Short source code examples

When I was trying to debug a problem that I thought was related to Flutter’s SharedPreferences library, I ended up rewriting a preferences method to use code like this rather than the normal approach:

Future<SharedPreferences> fPrefs = SharedPreferences.getInstance();
fPrefs.then((value) {rez = value.getBool(KEY_ENABLE_NOTIFICATIONS) ?? false; })
   .catchError((e) {
       debugPrint("===== ERROR: ${e.error}");
       return 60;
   });
return rez;

While that ended up being a waste of time, the benefit of my side excursion is that I get to show this example of how to use then and catchError with a Dart future. So if you wanted to see a Dart Future/then/catchError example, I hope this is helpful.

As a quick note, here are two examples of how to use a Future with a Duration delay in Dart (and Flutter):

// example 1
Future<bool> _getFutureBool() {
    return Future.delayed(Duration(milliseconds: 500))
        .then((onValue) => true);
}

// example 2
print('1');
Future.delayed(const Duration(milliseconds: 500), () {
    print('Hello, world');
});
print('2');

If you’re comfortable with Dart futures, you know that the second example will (eventually) print this output:

1
2
Hello, world

As a brief note to self, here’s an example of how to create a popup dialog (AlertDialog) using Dart and Flutter:

As a brief note to self, I was just trying to create a native image of a Scala application with GraalVM, and had this java.lang.NoClassDefFoundError error message:

Here’s a little Scala 3 (Dotty) enum match/case expression example:

As a note about Scala style, this Scala page strongly encourages that side-effect methods that takes no parameters should be declared with parentheses:

“However, this syntax (leaving off parentheses) should only be used when the method in question has no side-effects (purely-functional). In other words, it would be acceptable to omit parentheses when calling queue.size, but not when calling println() (or openGarageDoor()). This convention mirrors the method declaration convention given above.”

“Religiously observing this convention will dramatically improve code readability and will make it much easier to understand at a glance the most basic operation of any given method. Resist the urge to omit parentheses simply to save two characters!”

As a brief note to self, I was experimenting with passing methods as parameters to Scala functions — in particular trying to overload those method signatures to see what would work and what would not work — and I came up with these simple function signature overloading tests:

As a brief note to self, you compile a TypeScript source code file with the tsc command:

tsc Foo.ts

Depending on what you’re doing, you can also run the resulting JavaScript file from the command line with this node command:

tsc Foo.ts && node Foo.js

That command can be read as, “Compile the TypeScript file and then if that compiles successfully, run the resulting JavaScript file.” Note the ts and js extensions on those files.

As a brief note today, here’s a Scala method that writes the strings in a list — more accurately, a Seq[String] — to a file:

def writeFile(filename: String, lines: Seq[String]): Unit = {
    val file = new File(filename)
    val bw = new BufferedWriter(new FileWriter(file))
    for (line <- lines) {
        bw.write(line)
    }
    bw.close()
}

Here’s a brief example of how to sort data that’s already in a Java HashMap. First, some HashMap data:

import java.util.*;

Map<Integer, Float> playMap = new HashMap<Integer, Float>() {{
    put(10,  1f);
    put(12,  2f);
    put(15,  4f);
    put(18,  6f);
    put(20,  6f);
    put(25,  7f);
    put(30,  6f);
    put(35,  5f);
    put(40,  5f);
}};

A HashMap won’t keep that data in sorted order, so if you want your data sorted, one way to sort it is to add the elements to a Java TreeMap:

In an effort to share some source code (but without taking the time to explain it), here’s some Java source code that I just used to create a JFreeChart chart/graph of some data that I use in my Android football game:

If you need to copy a directory on Unix/Linux and want to preserve the date/time information while copying the directory and files, use the -p option to save the date/time information, and the -r option to copy the directory properly. For instance, I just used this cp command to copy a directory named OldDir to a new directory named NewDir, while retaining all of the date/time file information:

I was just going through some old notes and found this Scala DSL example from 2010:

As a brief note today, here’s an example of stackable modifications in Scala.

What is ‘super’ in Scala when you mix in traits?

Lately I was curious about what super means when you mix Scala traits into a class or object. A simplified answer is that super refers to the last trait that’s mixed in, though I should be careful and note that this is an oversimplification.

This can be demonstrated in an example that uses both inheritance and mixins with traits. Given this combination of traits and classes:

If you ever need to left-justify a multiline Scala string, the solution is to use the stripMargin method, as shown in this example:

def getWordFormatted(s: String): String = {
    s"""
      |
      |Word of the Day
      |---------------
      |Word: $s
    """.stripMargin
}

The | character has a special meaning when used in conjunction with stripMargin, so that method results in a string like this being output:

As a note to self, the Scala 3 “Dotty” procedure syntax is going to look like this:

def f() = { ... }
def f(): Unit = { ... }

This Scala 2 procedure syntax is being dropped:

def f() { ... }

You can find the official Dotty procedure syntax page at this link.

As for me, I’m adding this page right now because I noticed today that this procedure syntax (without the parentheses) also works with Dotty:

I can never remember how to create a Scala 3 (Dotty) project with SBT (in early 2019), so:

# create a new Dotty project
sbt new lampepfl/dotty.g8

# create a dotty project that cross compiles with scala 2
sbt new lampepfl/dotty-cross.g8

# start a dotty reply from within your sbt project
$ sbt

> console
scala> _

Here’s what an example interaction looks like — include SBT renaming my directory name to all lowercase, which brings me no joy:

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: