Apache Beam samples are now available in Kotlin!

Kotlin

If you are someone who’s been working with Java in your professional career; there’s a good chance that you’ve also heard of Kotlin, which is an Open Sourced, statically typed language for JVM and is mostly being favoured by Android Developers due to the many myriad features which enable more concise and cleaner code than Java without sacrificing performance or safety.

It gives us an immense pleasure to announce that we are also taking a step ahead in the same direction and releasing the samples for the Beam SDK in Kotlin alongside Java!

(Note : At the time of writing this post, only the WordCount samples have been added in Koltin with more samples underway)

Code Snippets

Here are few brief snippets of code that show how the Kotlin Samples compare to Java

Java

 String filename = String.format(
                    "%s-%s-of-%s%s",
                    filenamePrefixForWindow(intervalWindow),
                    shardNumber,
                    numShards,
                    outputFileHints.suggestedFilenameSuffix);

Kotlin

 // String templating
 val filename = "$filenamePrefixForWindow(intervalWindow)-$shardNumber-of-$numShards${outputFileHints.suggestedFilenameSuffix)"  

Java

public static class FormatAsTextFn extends SimpleFunction<KV<String, Long>, String> {
    @Override
    public String apply(KV<String, Long> input) {
        return input.getKey() + ": " + input.getValue();
    }
}

Kotlin

public class FormatAsTextFn : SimpleFunction<KV<String, Long>, String>() {
    override fun apply(input: KV<String, Long>) = "${input.key} : ${input.value}"  //Single line functions
}

Java

if(tableRow != null){
    formatAndInsert(tableRow);
}

Kotlin

tableRow?.let{
    formatAndInsert(it)  // No need for null checks
}

Java

String tableName = "testTable";

Kotlin

val tableName = "testTable"  // Type inferencing

Contributors Welcomed!

While we’re still adding more samples and streamlining the current ones, we would love to have your feedback on the code snippets. You can find them over here : https://github.com/apache/beam/tree/master/examples/kotlin

If you are using Kotlin with Apache Beam already; we would very much appreciate if you went ahead and help us convert the existing samples from Java into Koltin.

Thank you, and we are looking forward to feedback from you!