Merry Christmas

Merry Christmas everyone. I wish you all peaceful, quiet holidays.

Looking for something interesting to read? Check out the latest issue of our Kaffeeklatsch, a german magazine about all things software development.


Quick tip: Swift REPL

If you are on a Mac, have Xcode installed, and are looking for a lightweight solution to experiment with Swift, just use the Swift REPL. It's been there for almost 3 years, by the way. The tool resides in /usr/bin, so to invoke it just type swift.
To exit the REPL, just enter :q. Use :help to get help.


Two new articles on Android programming

You may have noticed the lack of posts during summer. Partly, that was because I was doing other stuff, for example writing articles and preparing talks. Turns out the articles are published at the same time. The latest issue of German magazine iX contains How to write fast and power saving Android apps and a review of Android Oreo taking a developers' perspective. Please check them out. If you have feedback or want to discuss them please feel free to contact me. I am more than happy to talk.


Flutter quick tip: fix blank screen in Android Emulator

If your Flutter app just shows a black screen in the Android Emulator, just add the --enable-software-rendering flag to your configuration. The following screenshot shows where to apply this in IntelliJ.

Configuration in IntelliJ


Quick tip: Using Android support library 26.x.y

While I was updating TKWeek to use Android O features, I also needed to update the Google support library to version 26.1.0.

It turns out you need to modify the toplevel build.gradle file as follwos:

allprojects {
     repositories {
         maven {
             url '


Some thoughts on Java and C#

In a couple of weeks I will be giving a talk about best practices in native Android app development using Xamarin during Developer Week 2017 in Nuremberg. So, time to freshen up my C# knowledge. Care to join me? Fine. Let's take a look at a very basic Android activity, written in Java:

package com.thomaskuenneth.testapp1;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {

The Java™ Tutorials explain:
A package is a namespace that organizes a set of related classes and interfaces. 
To which package a class or interface belongs is specified using the package keyword. As you can see in my example, such names can be rather long (com.thomaskuenneth.testapp1). A package name follows some conventions, for example it resembles domain names in reverse order. Also, it is lower case only. To free the developer from the hassle of having to type it every time a class is referenced, the import statement may be used. In the line starting with public class I refer to Activity, whose fully qualified class name is android.app.Activity.
The extends keyword makes MainActivity a child of Activity. As Java is a single inheritance language, there is only one direct ancestor. @Override is an annotation. It documents that the method onCreate() is present in the parent class, too. super.onCreate() invokes the implementation of the parent.
Finally, protected is an access modifier that controls who (that is, objects) can call that method. Now, let us turn to C#.

using Android.App;
using Android.Widget;
using Android.OS;

namespace TestApp1
    [Activity(Label = "TestApp1", MainLauncher = true)]
    public class MainActivity : Activity
        protected override void OnCreate(Bundle savedInstanceState)

C# has the concept of namespaces, too. In my example a namespace called TestApp1 is declared. Real-world-applications should follow Microsoft's namespace conventions. To reference other namespaces, the using directive is used. However, Android.OS is not a class but a namespace. To achieve a similar effect in Java one would write import android.app.*;. If the wildcard should be used still is debated heavily, at least now and then. Before moving on, I feel the need to remind you that the mechanics in Java and C# are not equal, so please refer to the language specifications of C# and Java for further detail. In particular, C# knows something like

using (MyResource myRes = new MyResource())

This ensures that myRes is disposed automatically as soon as it is no longer accessible. try-with-resources, anyone? :-)

Inheritance is documented in C# with a colon. MainActivity is a direct descendent of Android.App.Activity. What super is for Java, is base for C#. Both refer to the direct ancestor.

Have you spotted the line starting with [ and ending with ]? Here we see so-called attributes. Frankly, they remind me of annotations, but I would love to hear someone comment on this. See the docs for further reference. Finally, a minor, yet important difference: remember when to start something with a uppercase letter. In Java it is setContentView() and onCreate(), whereas in C# we have OnCreate() and SetContentView().

There are more similarities and differences. Which of then do you find hard to remember? Tell me, I'd love to hear them...


A couple of screenshots from Android Studio 3.0

The final Android O SDK should arrive sometime in July or August, with Android O to follow shortly after. Along with the new Android version we will see a new major version of Android Studio. Google has released a preview recently, so why not take it for a spin? The following two screenshots show the known project assistant. Have you spotted the added support for Kotlin, as announced during I/O 2017?

Spot the new Kotlin support option

Choosing the platform

The main windows has not changed a lot. Winking smile Then again, please take a closer look at the editor window, in particular the filename.

Android Studio main window

.kt is the extension for Kotlin source files. And : means extends. Classes in Kotlin can have properties. These can be declared as mutable, using the var keyword or read-only using the val keyword. Remember, Swift uses let for the latter one. Winking smile

Are you going to switch to Kotlin? I’d love to hear your opinions.


Quick tip: Setting the application implementation version for native app bundles

If you have set up your NetBeans project to use native packaging, you can set the implementation version of your app by adding a line such as


to nbproject/project.properties. The version is for example used in the filename for .msi installation files. And you can access it from inside your Java code:

String version = getClass().getPackage().getImplementationVersion();
if (version == null) {
    version = …

Can you share some tips regarding NetBeans native packaging? I’d love to hear them…


Drawing on screen

In this post I would like to share my experience regarding drawing on screen.

Now, what do I mean by this? First, consider a pair programming session. Your fellow programmer and you are sitting in front of the screen. You wish to discuss something that is currently on display. For whatever reason your colleague does not get what you want to tell. So you end up pointing at an area on the screen with your finger. While this may work during a one on one, it does not scale well in mob programming sessions. So, you might end up using a laser pointer, just as you might do during ordinary presentations.

But… Why not simply draw on screen?

The idea is far from new, presentation programs have just the right tools for this. The following screenshot shows what Powerpoint offers while in presentation mode.

Choosing how to draw on screen in Powerpoint

Then again, my initial scenario did not involve a presentation. Windows 10 Anniversary Update introduced the Windows Ink Workspace, which you can see in the following screenshot:

Windows Ink Workspace

Screen Sketch takes a screenshot and gives you a couple of drawing tools you can use to annotate, save and share it. However, as you can see in the following screenshot, editing does not take place full screen. The upper right portion of the screen contains the drawing tools. The bottom shows the grayed out taskbar. On my monitor, a saved screenshot was 1728 by 972 pixel, compared to its original resolution of 1920 by 1080 pixel. That border in my opinion limits the impression of directly drawing on screen.

Drawing on a screenshot

A very good alternative in my opinion is Epic Pen. Here is how it looks like:

Screenshot of Epic Pen

The program is (at the time of writing this) free for personal use and has a nice clean interface.

If you are on a Mac, I suggest taking a look at Highlight by Nicolas Zinovieff. It has an even more reduced user interface and offers few paint modes. But in my experience, painting on screen does not require much features. Draw something freehand, draw a circle or a line. That’s it. Remember, I used this to draw someone’s attention to something on display – nothing more.

Do you use similar tools? Which one do you prefer?


for ever young – musings about for loops

Welcome to another installment of my series about polyglot madness. Winking smile

Today we will take a look at one way to do things repeatedly. Let’s tart with BASIC yet again.

10 FOR I = 1 TO 3

The FOR keyword defines both start and end value. Anything that follows until the NEXT keyword is executed repeatedly, in my case, that is just printing a number. Have you noticed the loop variable after NEXT? Most BASIC dialects allow to omit it. In this case the most recent loop is used. Now take a look at this one:

10 FOR I = 1 TO 5 STEP 2
15 FOR J = 1 TO 3

Screenshot of an Oric emulator

The STEP keyword is used to change the increment or decrement value. Before we go back to the future, please note that start, end and increment value are computed prior to the execution of the loop.

Here is how JavaScript handles for loops:

for (i = 1; i <= 3; i++) {

This surely looks familiar to C, Java and C# developers. There is a nice alternative usage, this time written in Java:

String [] a = {"Java", "C#", "JavaScript", "..."};
  for (String b : a) {

If we translate this into JavaScript, we get something like:

var a = ["Java", "C#", "JavaScript", "..."];
for (var b in a) {

If we run it, we get… the numbers 0 to 3. Oh my.  In defense of JavaScript I should say that I misused in. The for...in statement is meant to be used to iterate over object properties. To get my above example working as intended, we have to use of instead of in.

Now let’s turn to Swift. Take a look at the following code fragment.

let a = ["Java", "C#", "JavaScript", "..."]
for b in a {

This resembles my JavaScript example. But please not the missing paranthesis. To count from 1 to 10 is as simple as:

for b in 1...10 {

However, counting down from 10 to 1 has a caveat. Using 10...1, the code will crash. To achieve this, we can use the reversed() instance method:

for b in (1...10).reversed() {

Next: Dart:

var a = ["Java", "C#", "JavaScript", "..."];
for (var b in a) {

Looks familiar, right? As Dart is greatly influenced by C-like languages, the three-part variant works as well:

for (var i = 1; i <= 10; i++) {

That’s it for today. Stay tuned.


Some reflections on functions

Regular readers know my fascination for home computers. So, please take a look at the following small BASIC program:

20 GOSUB 70
30 FOR I = 1 TO 3
40 GOSUB 70
60 END

Screenshot taken from a emulated C64

In BASIC you can reuse code through so-called subroutines. They are invoked using the GOSUB keyword. END marks the end of the subroutine. As you can see in the above example, subroutines can be called from different parts of the program. However, subroutines are no functions, as they lack the ability to return a vlaue and to receive parameters. This is done as follows:

10 DEF FN POW2(X) = X * X

So, DEF FN defines a function, whereas FN invokes it.

JavaScript has the function keyword. It is used as follows:

function pow2(x) { return x * x; }

To invoke the function use something like pow2(3)

Swift is similar, but uses the func keyword:

func pow2(x: Double) -> Double { return x * x; }
print(pow2(x: 3.0))

Dart can be very terse:

pow2(x) => x * x;

Or more descriptive:

double pow2(double x) {
  return x * x;

Finally, Scheme:

(define pow2 (lambda (x) (* x x)))
(pow2 3)

What other language feature would you like to see compared? Feel free to suggest your favorites...


Developing Flutter apps on Windows

Just a quick reminder that it is now possible to develop Flutter apps on Windows, too. The setup consists of a couple of easy steps and is well documented here. If you have already installed Android Studio, it boils down to:
  • Cloning the Flutter repo
  • Setting the PATH environment variable
  • Running flutter doctor
  • Picking your favorite editor and installing a Flutter plugin
I prefer IntelliJ, which offers a seamless integration of Flutter. Below is the screenshot of my sample Flutter app called Temperature Converter.
Screenshot of my temperature converter
Please keep in mind, that you cannot build iOS apps on a Windows machine.

Quick tip: stop your Android SDK Tools Blues

As you all know, SDK Tools, Revision 25.3.0 (March 2017) brought significant changes to the Android SDK commandline tools. Most notably, the android command is no more.

I used that command frequently in order to list my Android virtual devices: android list avd.

To do that now, just use emulator -list-avds

To launch the emulator with an avd, type emulator @avd_name, where avd_name is returned by the above command.


Setting the Java version for NetBeans

Just a friendly reminder, primarily to myself- ;-) You can override the Java version to be used for running NetBeans in the file etc/netbeans.conf.

As you know I gave two talks during our company conference MATHEMA Campus. One was about jshell which naturally ;-) required me to install Java 9 early access. Today, back in the office, I wanted to do some programming. I launched NetBeans on my Mac - and after a couple of seconds it terminated. It was clear that this had to have to do with the early access install. However, I did not want to remove it. So - what to do?

/usr/libexec/java_home, as you may know, lists installed Java versions. It (expectedly) pointed to /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home.

I hat already set JAVA_HOME to the Java 8 installation, but this certainly has no effect on app bundles. This is where etc/netbeans.conf comes in handy. It's inside the NetBeans installation directory, for example /Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans.

Just remove the hash symbol at the beginning of the line #netbeans_jdkhome= and enter the path to a jdk installation. On my machine this currently is /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home.


LET it be

In my previous post Some thoughts on being a polyglot developer I pondered about the usage of arrow constructs in programming languages. This time I will reflect on the let keyword.

As you know, I love home computers. So, let’s (ah, no pun intended) start with them. The following screenshot, by the way, shows the Oric emulator Oricutron by Peter Gordon.

Screenshot of the Oric emulator Oricutron by Peter Gordon

Most (but certainly not all) home computers offered a builtin BASIC interpreter and a (full screen) editor. As BASIC aimed to be easily learnable and understanable, the language sounds like short english sentences. For example, to assign a value to a variable, one might say Let A be Hello World. This translates to let a$ = “Hello World”. The dollar sign is needed to represent sequences of characters.

Other languages use let for assignment, too. There is an interesting question In what programming language did “let” first appear? on Software Engineering. Well. So far, so good. But we don’t use BASIC, do we?

Winking smile

ES6 brought let to the web. Instead of var we can now say

class black {}
let orange = new black();

The difference between both keywords is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block (which can be smaller than a function block). Both are global if the are outside any block. Variables declared with let are not accessible before they have been declared in their enclosing block. Further assignments to an already declared variable (using let) are valid. Why am I emphasizing this? Let us take a look at Swift. This language knows let, too. However assignments can be made only once. As you can see in the following screenshot, for non-constant-like usages we need to take var instead.

A Swift session at https://iswift.org/playground

The Dart programming language is optionally typed. That means that we can either write

var a = 42;


int a = 42;

Both result in int being printed.

To declare constants, Dart has the const keyword:

const a = 42;

Again, int is printed. Dart offers compiletime constants, so const a = new Random().nextInt(10); is not valid. A similar expression in ES6, however, is valid:

const c2 = Math.random();

The same is true for Swift’s let. The assigned value can be computed during runtime.

let a = random()

Speaking of const, remember that const is a reserved keyword in Java, but currently not used. C#, on the other hand, does:

public const double Pi = 3.14159;
Well, that has been enough of brain dance for now. 
Happy coding!


Some thoughts on being a polyglot developer

A few days ago I gave two talks during our company conference MATHEMA Campus. One introduced the jshell, the other one offered a glipse at the Dart programming language. While demoing jshel I entered a lambda expression. I srewed up the input, using => instead of ->. The reason: in Dart => is used for one line functions, as in

test(var i) => i * i;

main() {

The Dart talk was scheduled for the following day so my brain must have pressed fast forward.


C#, by the way, uses => for lambda expressions. C, on the other hand, uses -> in conjunction with a pointer to access members of a sctruct or union. Then again, ES6 introduced arrow functions that look like this one:

let test = (x,y) => x*y;

One more thing... Swift also knows ->. Here it is a function type. AnyObject -> Void is the type of a function that accepts AnyObject and returns Void.

That's it for today, I think my next post will be called LET it be. Guess what I will cover...


If you mixed language constructs while try to be a polyglot developer, please feel free to share them


An update to my Temperature Converter

Today I updated my Flutter sample app called Temperature Converter. It now makes use of Flutter's InputDecoration to show an error message if the input value is no floating point number. Here is how it looks like:
The following screenshot shows a valid input.
As you can see, the app disables the Calculate button accordingly. This is done by setting the onPressed parameter to null. To find out more, please grab the source at GitHub.


Quick tip: copy ip address to clipboard

My Mac runs Windows 10 in a virtual machine that is connected to the host using a network bridge. This way both host and client share the same network. Now you may be asking why I would need that. On Windows I use Visual Studio and Xamarin to create native iOS and Android apps. Using the Xamarin Mac agent I can both build and run the iOS app. But Android? The virtualized Windows can neither run Intel HAXM nor Hyper-V as VirtualBox does not support this type of nested virtualization. However, on the host (macOS) I can easily launch another VirtualBox client, for example Android x86. After adb connect ... I can use the simulated device to launch and debug apps. Here is a small shell function that copies the ip address to the clipboard:

function ipaddress {
    ipconfig getifaddr en0 | pbcopy


C64 Tribute Watch Face updated

A couple of years ago I bought an Android Wear device. Naturally, I wanted to see how to write apps for this smartwatch. That app is part of my book about Android programming. When I finalized the version for Android 7 a few months ago, Android Wear 2.0 was still in beta. This has changed recently, so I updated the app accordingly. You can find the source on GitHub. The app itself can be downloaded from the Play Store. Here’s how it looks like:
The watchface
The settings
Watchface chooser
Of course you need an Android Wear smartwatch to give it a try.

Quick tip regarding Android Wear watch faces: PROVIDE_BACKGROUND apparently not needed

Stumbled upon this one by chance. Turns out com.google.android.permission.PROVIDE_BACKGROUND is not needed.


Quick tip: Call a rest service with curl

curl \
--header "Content-type: application/json" \
--request POST \
--data '{"id": 42, "active": true}' \


Dart for Java developers: Mobile apps with Flutter

In a previous installment of my series of posts about Dart for Java developers we took a brief look at how to write a simple web application using Dart. This time, I would like to introduce you to the Dart way of going mobile. It's called Flutter. Flutter had its first public appearance in 2015. At that time it was called Sky. Since then Flutter has evolved quite a bit. Although still being a technical preview it is possible to write real world applications. As with all prerelease solutions, some things will likely change. On the other hand, being an early adopter also means building up skills early.

The underlying idea of Flutter is to build Material Design mobile apps for Android and iOS with one code base using Dart as the programming language. On both platforms the user interface is not made of native components. Flutter handles all painting by itself. Nonetheless Flutter tries to provide expected behavior, for example by using appropriate gestures, animations and transitions. This approach has both pros and cons. I am not going to discuss them here, but leave pondering up to you.

At this point, you are probably asking yourslef how a Flutter application looks both in source code and up and running. I have created a Flutter version of the temperature conversion app. You can find it on GitHub. Here is a screenshot of the app running in the iOS Simulator:

Screenshot of the temperature conversion app

Before taking a look at the code, I would like to talk about system requirements. Currently you need a macOS or Linux machine. Support for Windows appears to be work in progress. Setting things up currently requires quite a few steps, but these are well documented. Finally, let’s take a look at the code. The basic structure of a Flutter app looks like this:

import 'package:flutter/material.dart';
import ...


void main() {
  runApp(new MyApp());

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: _appName,
      home: new MyHomePage(title: _appName),

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
final String title;
  _MyHomePageState createState() => new _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> {

  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(config.title),
      body: new Block(

The top-level function main() is the entry point of the application. We instantiate a class that extends StatelessWidget. As the name implies, such widgets have no mutable state. Its build()-method returns yet another widget: MaterialApp. It has a title and a home. The latter one is a StatefulWidget. It overrides createState(), which to no surprise returns a freshly created State. Its build()-method returns a Widget that represents the current state. This may look complicated at first sight, but in fact its super simple. Changes to the state result in build() being called. As you can see in my sample app at GitHub, there is a corresponding setSate() to set this chain in motion.


Dart for Java developers: a visibilty primer

In the previous installments of my small series about Dart for Java developers we saw quite a few lines of code. ...that is, if you looked at the .dart files I linked to. ;-) You may have wondered why some identifiers start with an underscore. I briefly mentioned libraries and packages, but did not say much about visibility or scope. The underlying questions are
  • Where can I see a variable, function or method?
  • Where and when can I access them?
Consider the following source file named a.dart:

var answer = 42;
main() {
  var a = answer;
    var b = a;

It will print 42 once, but then fail with a NoSuchMethodError. That happens because there is no top-level getter b. To a Java developer it will not be surprising that print(b); outside the nested block fails, as b is not visible here. But why do we see NoSuchMethodError? Didn't I just access an identifier?

In Dart access to variables occurs via getters and setters, and if these have not been defined by the developer, they will be there automatically. If we remove the second print(), the program will run just fine (assume a version named a_correct.dart). Now take a look at the following lines of code:

import "a_correct.dart";
main() {

If we run it, 42 is printed once. In a_correct.dart answer has been declared at the top-level, so the identifier can be seen by the library that imports a_correct.dart. But what if we don't want a variable or function be visible? Just prefix the identifier with an underscore. Imagine a file b.dart:

var _answer = 42;
_hello() {

And c.dart:

import "b.dart";
main() {

Not to much surprise, it will fail. Neither _hello() nor _answer are visible. There is more control about what packages export to the outside world, but this is an advanced topic I might cover later. So, for now dear Java devs, just forget about publicprivate and protected. And stick to this simple rule:

If it's local, prefix the identifier with an underscore.

Clear. Precise.


Dart for Java developers: a simple web app

In the previous installment of my small series of posts about Dart for Java developers we have put together the pieces we crafted so far. We saw a small console application which used both model and converter libraries. As a next step we will be building a small web application. The following screenshot shows the running program.

a temperature converter web app

The corresponding html file is fairly simple. If you take a look at the body you find three tags: h1, form and p. The latter one will receive the computed temperature. The headline is merely decorative. The form comprises a text input field for the input temperature, two fieldsets which contain radio buttons for the input and output temperature units, and a button. There is no css to make the ui a little more fancy. Relating pull requests would be greatly appreciated.

So far, so easy. But how do we connect the html file to a Dart program, and how does this look like? The head contains two script references:

<script defer type="application/dart" src="main3.dart"></script>
<script defer src="packages/browser/dart.js"></script>

The latter one bootstraps the Dart runtime, whereas main3.dart (yes, that name is not extraordinarily desriptive ;-)) refers to the program. Let's take a look at it. There is a toplevel main() function, which connects the code to ui elements through querySelector(). To be able to use this function, we must import the dart:html package. Have you spotted the two calls to listen()? One is used to receive button clicks, while the other one will give us events when a key icharacter is entered. We use this to disable the button if the input field is empty. The remaining code is straight forward. We instantiate a model class, set it up, and have it calculate the output temperature.

Isn’t that easy?


Dart for Java developers: putting it all together

Welcome back to my small series of posts about Dart for Java developers. In the previous installment I promised to actually use the Model class soon. A very simple scenario can be seen in the file main2.dart. If main2.dart is invoked from the command line, one must pass exactly three arguments:

  1. input temperature unit
  2. value of the input temperature
  3. output temperature unit
The program is quite simple. We have two import statements as we need both model.dart and converter.dart. The first one gives us (among other things) the definition of a class named Model. We instantiate it using the familiar new keyword. After that we set the unit for both input and output temperature. enumFor() is a top-level function defined in model.dart. It checks if one of the enum values ends with the string passed as the only formal parameter. Remember that we pass them to the program via the command line. So to satisfy the string comparison, we need to enter exactly degreesCelsius, degreesFahrenheit or kelvin.

The temperature value itself is converted from String to double through stringToDouble(). This function can be found in converter.dart. It uses an internationalization package named intl. This package is capable of honoring locale-specific settings like the decimal mark and the thousands separator. My example explicitly sets the locale to German, which means that english 1,234.56 has to be entered as 1.234,56. Feel free to experiment with this. Why not reading the name of the locale from the command line?

Once the model has been set up, calculateOutTemperature() can be called to do the actual computation. After that, the result can be printed from the getter outTemperatureAsString(). Dart has first-class support of getters and setters, so no method parenthesis are needed.


Dart for Java Developers: The Model class

In my previous post, Dart for Java Developers: Into the code, we looked at two Dart source files, converter.dart and main.dart. Both contained so-called top level functions, that is, making code available without the need to put it in a class. Recall that each Dart file is a library. A library with a top level main() function is a script. Libraries are combined or grouped to form so-called packages. Packages can be easily distributed and reused. The Dart SDK comes with a package and asset manager called pub. Packages are described in a specification file named pubspec.yaml. It consists of, among other entries, a name, a version and a list of dependencies. For example, Temperature Converter relies on the internationalization package intl. A package can live anywhere. Some packages are on GitHub. Others reside at pub.dartlang.org. You can publish your packages there, too. Here is a description what you need to do: https://www.dartlang.org/tools/pub/publishing. The pub tool is invoked either through the plugin of your IDE (if you open a pubspec in IntelliJ you get a commands list at the top of the editor window), or from the console. If you fancy the shell, remember to include /bin in your PATH environment variable.

Now, let's turn to code. Recall that my original Temperature Converter app was written in Java using JavaFX. There is a Model class that uses Converter. So, Model has both state and behavior. The class is used as follows:

  1. Instantiate it
  2. Set the domain data (unit of input and output temperature and the temperature itself)
  3. Perform the calculation
  4. Grab the output string
  5. Back to 2.

Let's see how this looks like in Dart. We start with a library statement (which gives the library a name), followed by an import. We rely on the converter library you have encountered in the previous post. After that you see an enum definition. Compared to, for example Java, Dart enums allow less customization. Currently the string representation of the enum evaluates to enum_name.enum_value. To be able to more easily map user interface elements to enum values (you will see that later) I implemented a convenience method named enumFor(). Dart enums cannot be defined inside classes. Now let's take a look at the Model class (it's inside model.dart). Besides the lack of access level modifiers (more on that soon) the code looks comfortingly familiar. With two very welcomed exceptions. Have you spotted the get and set keywords? Dart has language level support for getters and setters.

In the next installment we will actually use the new Model class. But if you cannot wait to try it out, just grab the code from GitHub and start playing.


Dart for Java Developers: Into the code

In a previous post, Dart for Java Developers: First Contact I offered you a glimpse at the language by creating a very basic project using the project creation wizard of IntelliJ IDEA. Today I would like to dig a little deeper by showing you how to rewrite a Java program in Dart. I will use a small temperature conversion app which I wrote for a series of talks about Java on mobile devices. You can find the JavaFX version on GitHub.

The program consists of four classes, a user interface definition and a resource bundle. TemperatureConverter is the main class. It loads the ui from an fxml file and instantiates a controller class called FXMLDocumentController. This controller binds ui components and actions to a model class named Model. This class holds the actual domain data and invokes code from the Converter class. It contains a couple of static methods that do the actual temperature calculation. Let us start with this one.

As you can see in the source, although doing different computations, the innards of the methods are mostly the same, that is, doing some arithmetics using the primitive double data type. The method stringToDouble() converts a string to a double value honoring locale specific settings like the decimal mark and the thousands separator. doubleToString() creates a string consisting of a double value with its fractional part omitted if it is zero, and a suffix. How could we do this in Dart?

For your convenience I set up a GitHub repository. Please take a look at converter.dart. Possibly to a bit of a surprise, it does not contain a class, but several top level functions. unitDegreesCelsius, unitDegreesFahrenheit and unitKelvin are compile time constants. _f is declared final, so its value can be assigned only once, but obviously not during compile time. I really like the compact function definition using =>, which takes an expression. If more statements are needed, the traditional body using curly braces comes into play. Also very nice is the string interpolation you can see in _doubleToString(). You can access the value of an expression inside a string by using ${expression}. If the expression is an identifier, the {} can be omitted.

To see the calculations in action I have provided main.dart. If a dart file contains a toplevel main()-function it is called a script. The following screenshot shows the execution of the program in Visual Studio Code.
Editing and running the script in Visual Studio Code

Dart programs and libraries are often distributed as packages. Packages follow certain rules regarding structure and content. You can see a bit of this in the screenshot. I might go into a little more detail in a future post. The json file you can see in the screenshot is not part of that package but helps running the program in Visual Studio Code. Want to try for yourself? Great. Just clone the repo and start playing.


TKWeek 1.9.0 released to Google Play

It has been far too long since I last updated TKWeek. Finally, 1.9.0 is now available in the Play store. A remarkable new feature, in fact the hightlight of this version, are notifications about upcoming events. Here is how this looks like:

Summarized notifications on Android 7.1

Expanded notifications on Android 7.1

The notifications are bundled notifications on Android 7.1. Older versions show the traditional bigview notifications, which unfortunately cannot be expanded.

Android Wear knows stacked notifications. Here is how this looks like:

Partly visible notification

Collapsed notification stack

Expanded notification stack