Short source code examples

Just fooling around a little bit at the moment, here are several ways to write for/do blocks with the “significant indentation” style in Dotty (Scala 3) as of Dotty v20:

Sometimes a Dart or Flutter API may require you to return a Future even if you already have a known, constant, or literal value. If/when that happens, you can use this approach:

return new Future(() { return 42; });

In this example the known value is 42, but it could have been a string like "Hello", a boolean like true, or any other known or literal value.

I was surprised to learn that Dart doesn’t have a string capitalize method, so if you ever need a capitalize method/function, here’s a start towards a solution:

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

That function will work with Dart strings like these:

As a brief note, if you need a Dart function to get the current date/time in a “seconds since the epoch” format, I can confirm that this function works:

/// the current time, in “seconds since the epoch”
static int currentTimeInSeconds() {
    var ms = (new DateTime.now()).millisecondsSinceEpoch;
    return (ms / 1000).round();
}

Today I learned that for several reasons, Flutter Debug mode may be significantly slower than Production mode. As just one reason, Debug mode is compiled using JIT while Production mode uses AOT. You can read more about the reasons on the Flutter UI Performance page.

A very important note on that page is that if you’re using a real hardware device (as opposed to an emulator), you can run your code in Profile mode like this:

When using Flutter (and Dart), if you need to compare two TimeOfDay values, I can confirm that it helps to first convert the TimeOfDay to a double using this function:

/// note: 'hour' is in 24-hour format
double _timeOfDayToDouble(TimeOfDay tod) => tod.hour + tod.minute/60.0;

If you get a Flutter error like this one:

Unhandled Exception: MissingPluginException(No implementation found 
for method canLaunch on channel plugins.flutter.io/url_launcher)

fear not, I get it about once a week. For me it happens every time I add a new plugin to my Flutter project, and then forget to stop my application and restart it. Either that, or you might be working from the command line and forgot to run flutter pub get.

Usually what happens in my workflow is:

As a brief note, on this page I found this example of how to set the size of a Flutter Container:

Container(
    height: MediaQuery.of(context).copyWith().size.height / 3,
);

After looking at what the copyWith method does:

copyWith: Creates a copy of this media query data but with the given fields replaced with the new values.

If you ever need a Dart/Flutter method to format a TimeOfDay variable — i.e., convert a TimeOfDay to a String — I can confirm that this method works:

String formatTimeOfDay(TimeOfDay tod) {
    final now = new DateTime.now();
    final dt = DateTime(now.year, now.month, now.day, tod.hour, tod.minute);
    final format = DateFormat.jm();  //"6:00 AM"
    return format.format(dt);
}

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: