What happened at KotlinConf

All the talks at KotlinConf, organized and commented

The KotlinConf 2017 was on 2-3 november and it was a great conference. In this article we are going to present a short summary of the talks with links to their videos.

List of Talks

Understanding Kotlin

The talks you want to watch if you want to understand the language better: from introductory talks to deep dives.

Understand Every Line of Your Codebase

A talk by Boris Farber and Victoria Gonda, who also wrote the article: Java as your Kotlin Study Buddy. It is a talk centered on showing the Java equivalent of the Kotlin code you write and the bytecode produced by the Kotlin compiler. It is interesting especially for new Kotlin developers and people still using Java that want to see a bit of the Kotlin magic.

Introduction to Coroutines

A talk by Roman Elizarov, who works on the Kotlin language at JetBrains. It is about one of the most exciting features of Kotlin: coroutines. In this talk you can learn why you need coroutines and how to use them with live examples.

Deep Dives into Coroutines on JVM

A talk by Roman Elizarov, who works on the Kotlin language at JetBrains. This is the deep and technical companion of the other talk by Elizarov on coroutines. It is about the technical aspects of the coroutines implementation on top of the JVM. It is a great talk for people that want to understand how coroutines work.

Idiomatic Interop

A talk by Kevin Most on Java-Kotlin interop. Kotlin and Java interop is great, but it is not perfect especially when invoking Kotlin code from Java code. In this talk you are going to know how to make the two languages work better together: from the strategies to the gotchas. This talk is perfect for Kotlin developers that have to take in account their Java users.

Kotlin Puzzlers

A talk by Anton Keks on Kotlin puzzlers. This talk presents some interesting nuances of Kotlin through the use of small programs. It is a fun talk to watch if you want to test your understanding of Kotlin behavior. For instance, do you know what happens when you write return throw return "Hello" ? Watch this talk to find out.

The Cost of Kotlin Language Features

A talk by Duncan McGregor on the costs in terms of code size and execution time of Kotlin. The talk is focused on the bytecode produced by the Kotlin compiler on the JVM. The author actually said that you shouldn’t care about such costs, but if you do the talk will shows you the small costs in terms of performance that some features of Kotlin have.

You Can, but Should You?

A talk by Mike Gouline, a software engineer who works in the health industry. This is a talk on how to be smarter in using Kotlin. It discusses and explains how to choose among the different features that Kotlin offers in a way that makes sense for your software. It does not just present the options (i.e., for vs foreach), but it gives you guidelines on how to make the choice.

It is a very interesting talk not only for Kotlin users, but for everybody that needs to learn how to better organized his code.

Deep Dive into Kotlin/Native

A talk by Andrey Breslav, the leader of Kotlin development at JetBrains. This is a talk about the inner workings of a prerelease feature of Kotlin/Native: now (soon) you could use it develop for iOS. The talk is linked to the keynote of the conference since it shows the internals of the app demoed there.

This is the best talk to watch if you are interested in understanding how Kotlin/Native and iOS work together.

Kotlin Types: Exposed

A talk by Svetlana Isakova, developer advocate at JetBrains and co-author of Kotlin in Action. This is a talk about Kotlin types interact with Java: what happens under the hood, what you should be aware of and explanations of some design choices made by JetBrains.

Android & Web

Talks specifically about Android, Web and KotlinJS.

Frontend Kotlin from the Trenches

A talk by Gaetan Zoritchak, on KotlinJS used for the frontend. This talk gives feedback on the journey and the technical challenges faced on developing a data visualization library: Data2viz.

A View State Machine for Network Calls on Android

A talk by Amanda Hill on how to build a View State Machine for network calls on Android. If you are wondering why you should do that she will show you right away by building an app. Basically, it is a way to handle networking request in a way that is resistant to UI changes.

Real World Kotlin-Powered Android

A talk by James Williams, responsible for Android Curriculum at Udacity. This is about converting an Android app written in Java to Kotlin, bit by bit. It is practical and interesting way to understand some of issues involved.

Isomorphic Kotlin

A talk by Troy Miles on the server side of an Android isomorphic mobile system. The talk starts with an introduction on the issue, then continues on showing how to build a microservice with Ratpack, wire it, and deploy it on Heroku.

Going Serverless with Kotlin

A talk by Marcos Placona, who works as a developer evangelist at Twilio. This is a talk on the tools and processes to build mobile and IoT stuff with Kotlin and deploy it on AWS Lambda to go serverless with Kotlin. There are a few minutes of introduction to the advantages of going serverless and then he shows code.

How to Build a React App in Kotlin

A talk by Dave Ford on why it makes sense to use Kotlin on the web and how to build a React App with your favorite language. The talk is focused on KotlinJS and the web world. The main point of the talk is that using Kotlin is even better than using a templating system to write web interfaces (i.e., HTML). Essentially templating system are simple languages, but Kotlin is a better language that has typesafe-builders, the (internal) HTML DSL (kotlinx.html) and a few React wrappers.

Given that most Kotlin developers come from Java, this is a very interesting idea that you probably never thought about.

Spring

A few talks dedicated to the Spring Framework and its usage with Kotlin.

Bootiful Kotlin

A talk by Josh Long, author of 5 books and “the guy with most bugs per line of code on the Spring team”.

It is a demo talk about using Spring Boot with Kotlin.

Asynchronous Programming with Kotlin Coroutines in Spring

A talk by Konrad Kamiński on using coroutines for asynchronous programming in Spring. It is a code-based talk on how to use coroutines in Spring. It is quite specific, so it is great if you are interested in just that, but it also useful for current Java and Spring users to get the feel of how it is to work with Kotlin.

Why Spring Loves Kotlin

A talk by Sebastien Deleuze, a Spring contributor working at Pivotal. This is a talk about using Kotlin for Spring applications. It starts with the reasons to choose Kotlin and then shows the various tools and features of the pair Kotlin and Spring. In this talk you will learn to transform a Spring Boot 1.0 Java + Javascript project into a Spring Boot 2.0 pure Kotlin project.

Working On Your Code

Talks about Kotlin tools, checking and generating your code programmatically.

Generating Kotlin Code

A talk by Alec Strong and Jake Wharton, developers respectively at Square and Google. This is a talk about code generation to generate an API. It is a pragmatic talk: almost every slide features code. It is mostly focused on the JVM, but it also address a bit the multi-platform issues.

What’s New & Cool in Kotlin Tools

A talk by Dmitry Jemerov, the leader of the tools team for Kotlin at JetBrains. It is a demo of the new features you will get on the release 1.2. It is also useful to get to know a few practical aspects of building the cross-platform Kotlin platform.

Kotlin Static Analysis with Android Lint

A talk by Tor Norbye, tech lead for Android Studio. It starts with a bit of the philosophy of Android Lint (i.e., focus on Android issues, leave the generic ones to the IDE) before going to the meat of the tool. The tool can now also be used outside of Android, so it can be useful for everybody who uses Kotlin.

Lessons Learned Building a Build Tool

A talk by Cedric Beust, the creator of Android Gmail and TestNG. The talk is about Kobalt, a building system written in Kotlin with a simple DSL, inspired by Maven and Gradle. The talk explain the reason why it was created and how it was made.

Building Kotlin Applications at Scale with Gradle

A talk by Hans Dockter, creator of Gradle and founder of the company behind it. This is a talk about how to use Gradle and the Gradle plugin for Kotlin to build large applications. It is divided in two parts: a description of features and issues and a second practical part where you see how things works on an example.

Testing Kotlin at Scale: Spek

A talk by Artem Zinnatullin, on how to test at scale. This talk is about the why and how you can migrate thousands of tests from JUnit to Spek. Spek is a testing framework inspired by RSpec, designed to better organize your tests. It is an interesting talk for everybody that want to do tests with Kotlin and understanding how they can use Spek to organize large scale testing.

Experiences

Talks that focus on an experience the speaker had: their work at a specific company or for a certain project. Usually they have less code, and concentrate more on soft-skills or strategic choices.

Cords & Gumballs

A talk by Mike Hearn on the benefits and challenges of using Kotlin for an enterprise software and a small side-project. The enterprise software is Corda, the distributed ledger platform designed to record, manage and automate legal agreements between business partners. The project is written in Kotlin, but it has to support perfectly Java developers in the finance world, so it is an interesting talk for people that work in the enterprise world.

My Transition from Swift to Kotlin

A talk by Hector Matos, a senior iOS developer. The talk is both a story of the transition and a comparison between Swift and Kotlin. It is a good talk to show to your manager, if you need to persuade him or her to let you develop with Kotlin.

My Life as a Tech Transfer Monad

A talk by Erik Meijer, a computer scientist who works at Facebook and now is “he is on a quest to make uncertainty a first-class citizen in mainstream programming languages”. It is an interesting talk and indeed one of the most popular, but it is hard to describe it.

It is a talk with a lot of computer science and essentially is about trying to understand (i.e., abstracting) programming: the successes and failures that the author has encountered in this quest.

It is a great talk if you want to level up your understanding of programming.

Building and Deploying Netflix

A talk by Rob Fletcher who works at Netflix (Danny Thomas is mentioned in the abstract, but he does not appear). The talk is essentially half about the Netflix way of doing things and half about the reasons why the author of this talk chose Kotlin instead of other languages to build some tools used at Netflix.

Kickstarting Kotlin Culture: The Journey from Java to Kotlin

A talk by Neil Power, who works at Hootsuite. This talk is about the experience of the adoption of Kotlin at Hootsuite. It is both a story of the journey from Java to Kotlin and the lesson learned to build a strategy to facilitate the migration from Java to Kotlin. It is an interesting talk for the people that are considering the implementation of such strategies in their workplace.

Sharing [Kotlin code across platforms] is Caring!

A talk by Eugenio Marletti, on how Kotlin can help with issues related to multi-platform apps. This is a talk on the experience of writing a multi-platform app, the problems related to developing it and how Kotlin can be used to write the business logic once. The rest will need to be specific for each platform.

Cats and Dogs

A talk by Michael May and Roman Piel, iOS and Android developers. A fun and practical talk on how Android and iOS teams can work together in a team: design the app together, maintain the API, etc. This is a talk about code and tecnical issues (e.g., how to design the API together), but also about the organizational aspects.

Kotlin World

Everything Kotlin: from new things you can do, to better ways to do the same things you already do. Talks about how to contribute to Kotlin or help your team work better, etc. There is something for everybody, whether you are searching for new ideas or to learn something.

Building Languages Using Kotlin

You may read about the experience and the best speech there: Building Languages Using Kotlin by Federico Tomassetti on another of our articles.

The Road to Kotlintown

A talk by Huyen Tue Dao and Christina Lee, developers at Pinterest and Atlassian. This is a code-base talk on how practically convert existing code to Kotlin and learn the Kotlin way of doing things. It is a pragmatic talk for new Kotlin users or people interested in joining the good side of the JVM.

How to Kontribute

A talk by Yoshinori Isogai on how to contribute to Kotlin development as an external contributor. This is a pragmatic talk on how to partecipate to Kotlin development, particularly on a Kotlin plugin. This is a very pragmatic talk dealing with things like setting up development environment (you will need the help), unit tests, etc. It is very useful if you want to contribute to the language.

Architectures Using Functional Programming Concepts

A talk by Jorge Castillo on functional programming for Kotlin. This a code-based talk on why you will want to use functional programming and how to use functionally concepts on Kotlin using Kategeory.io, a library that brings functional types to Kotlin. The examples are mostly based on Android issues, but they can be applicable to many situations.

RX Java with Kotlin in Baby Steps

A talk by Annyce Davis, a developer, author and speaker. This is an introductory talk about RxJava and reactive programming. It is a well designed lesson on the basics: operators, observers and observable.

Kotlin for the Pragmatic Functionalist

A talk by Paco Estévez García, a developer at Facebook. This is a talk on how you can pragmatically use functional programming with Kotlin: the language is ready today, this talk will show how to use it. He also show the issues still present. It mentions Kategory, a library which is the focus of another talk.

Kotlin EE: Boost your Productivity

A talk by Marcus Fihlon, a developer, lecturer and author. There is not an actual Kotlin EE framework, but this is a talk about using Kotlin with Java EE to create services of any size (nanoservices, microservices, etc.). This is a talk about theory and practice (i.e., code) to solve problems of enterprise developers.

Kotlinbots: Building Your Own Personal Robot Army

A talk by Adrián Catalan on how to use Android Things and how to develop software for Internet of Things devices (and robots). This is a pragmatic talk on how to develop with Android Things on Raspberry Pi to do things like switching on LEDs, so it slightly oversells the robot army things, but it is cool nonetheless. The talk also shows the hardware part of the work: how to wire the actual wires to the board and the theory you need to work with electric circuits. It is quite an interesting talk for people willing to getting started on IoT development.

Inter-Reactive Kotlin Applications

A talk by Julien Viet, the Vert.x project lead at RedHat. This is a talk about using Kotlin to write inter-reactive Vert.x applications: perform asynchronous operations and receive events in a synchronous way. Eclipse Vert.x is a set of libraries to write application on the JVM (not necessarily with the IDE Eclipse). The talk contains both the theory and the practical aspect of writing reactive applications using Kotlin features (i.e., coroutines).

Two Stones, One Bird: Implementation Tradeoffs

A talk by Christina Lee, an Android developer at Pinterest. The title of the talk is a play on the common saying. The talk is about how to choose between two different viable options to achieve on objective. It discusses the tradeoffs of a few common programming problems with multiple solutions such as with/apply and let/also.

Kotlin for Data Science

A talk by Thomas Nield, author and developer. The talk is starts with an introduction to data science and its issues, then continues on why and how to best use Kotlin for data science. This talk is great if you work in an organization that need one platform to get the data scientists and developers on the same page. The author of this talk suggests to also look at kscript – Scripting Enhancements for Kotlin.

kscript – Scripting Enhancements for Kotlin

A talk by Holger Brandl, data scientist at the Max Planck Institute. This is mainly a talk about kscript: a easy-to-use, very flexible, and almost zero-overhead solution to write self-contained mini-applications with Kotlin. Obviously it also has an introduction to why Kotlin was chosen and the tool developed for data science work. It is a great talk if you are interested in the practical aspects of doing data science with Kotlin, but also for general scripting.

Summary

KotlinConf was great and there was something for everybody: from real-word technical knowledge to experience ans help to better manage Kotlin projects and team. There were also interesting and unusual projects (i.e., robot army). The excitement for the future of Kotlin was palpable and we hope we are going to feel the same next year. What do you want to see next year?

Introduction to Coroutines

Introduction to Coroutines: What Problems Do They Solve?

Problem Solution
Simplify Callbacks Coroutines
Get results from a potentially infinite list BuildSequence
Get a promise for a future result Async/Await
Work with streams of data Channels and Pipelines
Act on multiple asynchronous inputs Select

The purpose of coroutines is to take care of the complications in working with asynchronous programming. You write code sequentially, like you usually do, and then leave to the coroutines the hard work. Coroutines are a low-level mechanism. The end objective is to build  accessible mechanisms like async/await in C#

Coroutines are an experimental feature, introduced with Kotlin version 1.1. They have been created to manage operations with long execution time (e.g., Input/Output operations with a remote resource) without blocking a thread. They allows to suspend a computation without keeping occupied a thread. In practical terms, they behave as if they were light threads with little overhead, which means that you can have many of them.

In fact, traditional threads have a flaw: they are costly to maintain. Thus it is not practical to have more than a few available and they are mostly controlled by the system. A coroutine offers a lightweight alternative that is cheap in terms of resources and it is easier to control by the developer.

Suspension Points

You have limited control over a thread: you can create a new one or terminate it, but that is basically it. If you want to do more you have to deal with system libraries and all the low-level issues that comes with them. For instance, you have to check for deadlock problems.

Coroutines are a easier to use, but there are a few rules. The basic ideas is that coroutines are blocks of code that can be suspended, without blocking a thread. The difference is that blocking a thread means the thread cannot do anything else, while suspending it means that it can do other things while waiting the completion of the suspended block.

However you cannot suspend a coroutine at arbitrary positions. A coroutine can be suspended only at certain points, called suspension points. That is to say functions with the modifier suspend.

suspend fun answer() {
      println("Hello to you!")
}

The behavior is controlled by the library: there might be a suspension in these points, but this is not a certainty. For example, the library can decide to proceed without suspension, if the result for the call in question is already available.

Functions with suspension points works normally except for one thing: they can only be called from coroutines or other functions with suspension points. They cannot be called by normal code. The calling function can be a (suspending) lambda.

Launching a Suspension Function

The simplest way to launch a suspension function is with the launch function. It requires as an argument a thread pool. Usually you pass the default CommonPool.

import kotlin.coroutines.experimental.* // notice that it is under a package experimental

suspend fun answer() {
      println("Hello to you!")
}

fun main(args: Array<String>) {
    launch(CommonPool) {
        answer() // it prints this second
    }

    println("Hello, dude!") // it prints this first
    Thread.sleep(2000L) // it simulates real work being done
}

Notice how the coroutines are inside a package called experimental, because the API could change. This is also the suggested approach for your own library functions that implement coroutines. You should put them under an experimental package to warn them of the instability and to prepare for future changes.

This is the basic way, but in many cases you do not need to deal directly with the low-level API. Instead you can use wrappers available for the most common situations.

In fact, coroutines are actually a low-level feature, so the module itself kotlin.coroutines offers few high-level functionalities. That is to say, features made for direct use by developers. It contains mostly functions meant for creators of libraries based upon coroutines (e.g., to create a coroutine or to manage its life). Most of the functionalities that you would want to use are in the package kotlinx.coroutines.

From Callbacks to Coroutines

Coroutines are useful to get rid of callbacks. Assume that you have a function that must perform some expensive computation: solveAllProblems. This function calls a callback that receives the result of the computation and performs what is needed (e.g., it saves the result in a database).

fun solveAllProblems(params: Params, callback: (Result) -> Unit)

You can easily eliminate the callback using the suspendCoroutine function. This function works by relying on a Continuation type (cont in the following example), that offers a resume method, which is used to return the expected result.

suspend fun solveAllProblems(params: Params): Result = suspendCoroutine { cont ->
    solveAllProblems(params) { cont.resume(it) }
} 

The advantage of this solution is that now the return type of this computation is explicit., but the computation itself is still asynchronous and does not block a thread.

Coroutines And Sequences

The function buildSequence in one of the high-level functionalities of the basic kotlin.coroutines package. It is used to create lazy sequences and relies on coroutines: each time it runs it return a new result. It is designed for when you can obtain partial results that you can use instantly, without having the complete data. For instance, you can use it to obtain a list of items from a database to display in a UI with infinite scrolling.

Essentially the power of the function rests on the yield mechanism. Each time you asks for an element the function executes until it can give me that element.

In practice, the function executes until it find the yield function, then it returns with the argument of that function. The next execution continues from the point it stopped previously. This happens until the end of the calls of the yield functions. So the yield functions are the suspension points.

Of course, the yield functions can actually continue indefinitely, if you need it. For instance, as in the following example, which calculates a series of powers of 2.

val powerOf2 = buildSequence {
    var a = 1
    yield(a) // the first execution stops here
    while (true) { // the second to N executions continue here
        a = a + a
        yield(a) // the second to N executions stop here
    }
}

println(powerOf2.take(5).toList()) // it prints [1, 2, 4, 8, 16]

It is important to understand that the function itself has no memory. This means that once a run it is completed, the next execution will start from scratch.

println(powerOf2.take(5).toList()) // it prints [1, 2, 4, 8, 16]
println(powerOf2.take(5).toList()) // it still prints [1, 2, 4, 8, 16]

If you want to keep getting new results, you have to use directly iterator() and next()methods on the sequence, as in the following example.

var memory = powerOf2.iterator()
println("${memory.next()} ${memory.next()} ${memory.next()}") // it prints "1 2 4"

The Async and Await Mechanism

Let’s see some of the functionalities of the package kotlinx.coroutines. These are are the heart of the coroutines: the primitive parts are there to implement these functionalities, but you typically do not want to use. The exception is if you are a library developer, so that you  can implement similar high-level functionalities for your own library.

For instance, it provides async and await, that works similarly to the homonym in C#. Typically they are used together, in the case in which an async function returns a meaningful value. First you invoke a function with async, then you read the result with await.

There is not an official documentation of these features, but you can find info about it on the GitHub project.

fun asyncAFunction(): Deferred<Int> = async(CommonPool) {
    10
}

You can see that:

  • the name of the function starts with async. This is the suggested naming convention.
  • it does not have the modifier suspend, thus it can be called everywhere
  • it returns Deferred<Int> instead of Int directly.

An example of how it can be used.

fun main(args: Array<String>) {

    // runBlocking prevents the closing of the program until execution is completed
    runBlocking {
        // one is of type Deferred<Int>
        val one = asyncAFunction()
        // we use await to wait for the result
        println("The value is ${one.await()")
    }
}

The first interesting fact is that one.await returns Int. So we can say that it unpacks the deferred type and make it usable as usual. The second one is the function runBlocking, that prevents the premature end of the program. In this simple case it is just an alternative to the usage of the old sleep trick (i.e., blocking the ending of the program with Thread.Sleep) to wait for the result of the asynchronous call. However the function can also be useful in a few situations with asynchronous programming. For instance, it allows to call a suspend function from anywhere.

The function essentially behaves like the following.

// example without await and runBlocking

fun main(args: Array<String>) {
    // one is of type Deferred<Int>
    val one = asyncAFunction()
    // wait completion
    while(one.isActive) {}
  
    println("The value is ${one.getCompleted()}")
}

In the previous example we basically simulated the await function:

  • we did nothing while the asynchronous function was active
  • we read the result once we were certain it was finished

Channels

Coroutines can also implement Go-like channels: a source that send content and a destination that receive it. Essentially channels are like non-blocking queues, that send and operate data asynchronously.

import kotlin.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.*

fun main(args: Array<String>) {
    runBlocking {
        val channel = Channel<Int>()
        launch(CommonPool) {            
            var y = 1
            for (x in 1..5) {
                y = y + y
                channel.send(y)
            }
            // we close the channel when finished
            channel.close()
        }
        // here we print the received data
        // you could also use channel.receive() to get the messages one by one
        for (y in channel)
            println(y)
    }
}

This code also produces the sequence of powers of 2, but it does it asynchronously.

A more correct way to produce the same results is using produce function. Basically it bring a little order and take care of making everything running smoothly.

fun produceAFewNumbers() = produce<Int>(CommonPool) {
    var y = 1
    for (x in 1..5) {
        y = y + y
        send(y)
    }
}

fun main(args: Array<String>) {
    runBlocking {
        val numbers = produceAFewNumbers()
        numbers.consumeEach { println(it) }
    }

The end result is the same, but it is much cleaner.

Pipelines

A common pattern with channels is the pipeline. A pipeline is made up of two coroutines: one that send and one that receive a stream of data. This is the more natural way to deal with an infinite stream of data.

import kotlin.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.*

fun produceNumbers() = produce<Int>(CommonPool) {
    var x = 1
    while (true)
        // we send an infinite stream of numbers
        send(x++)
}

The first coroutine is produceNumbers which sends an infinite stream of numbers, starting from 1. The function rely on the aptly named produce(CouroutineContext) , that accepts a thread pool and must send some data.

fun divisibleBy2(numbers: ReceiveChannel<Int>) = produce<Int>(CommonPool) {
    for (x in numbers)
    {
        if ( x % 2 == 0)
            // we filter out the number not divisible by 2
            send(x)
    }
}

The second coroutine receive the data from a channel, but also send it to another one, if they are divisible by 2. So a pipeline can actually be made up of more channels linked together in a cascade.

fun main(args: Array<String>) {
    runBlocking {
        val numbers = produceNumbers()
        val divisibles = divisibleBy2(numbers)
        // we print the first 5 numbers
        for (i in 1..5)
            println(divisibles.receive())

        println("Finished!") // we have finished
        // let's cancel the coroutines for good measure
        divisibles.cancel()
        numbers.cancel()
    }
}

The example is quite straightforward. In this last part we just put everything together to get the first five numbers that are produced by the pipeline. In this case we have sent 9 numbers from the first channel, but only 5 have come out of the complete pipeline.

Notice also that we did not close the channels, but directly cancelled the coroutines. That is because we are completely ending their usage instead of politely informing their users about the end of transmissions.

The Select Expression

Select is an expression that is able to wait for multiple suspending functions and to select the result from the first one that becomes available. An example of a scenario in which it can be useful is the backend of a queue. There are multiple producers sending messages and the backend processes them in the order they are arrived.

Let’s see a simple example: we have two kids, John and Mike, trading insults. We are going to see how John insult his friend, but Mike is equally (un)skilled.

fun john() = produce<String>(CommonPool) {
    while (true) {
        val insults = listOf("stupid", "idiot", "stinky")
        val random = Random()
        delay(random.nextInt(1000).toLong())
        send(insults[random.nextInt(3)])
    }
}

All they do is sending a random insult whenever they are ready.

suspend fun selectInsult(john: ReceiveChannel<String>, mike: ReceiveChannel<String>) {
    select<Unit> { //  <Unit> means that this select expression does not produce any result
        john.onReceive { value ->  // this is the first select clause
            println("John says '$value'")
        }
        mike.onReceive { value ->  // this is the second select clause
            println("Mike says '$value'")
        }
    }
}

Their insults are processed by the selectInsult function, that accepts the two channels as parameters and prints the insult whenever it receive one. Our select expression does not produce any result, but the expression could return one if needed.

The power of the select expression is in its clauses. In this example each clause is based upon onReceive, but it could also use OnReceiveOrNull. The second one is used to get a message when the channel is closed, but since we never close the channel we do not need it.

fun main(args: Array<String>) {
    runBlocking {
        val john = john()
        val mike = mike()
        repeat(6) {
            selectInsult(john, mike)
        }
    }

Putting all the pieces together is child play. We could print an infinite list of insults, but we are satisfied with 6.

The select expression clauses can also depend upon onAwait of a Deferred type. For example, we can modify our select expression to accept the input of an adult.

fun adult(): Deferred<String> = async(CommonPool) {
    // the adult stops the exchange after a while
    delay(Random().nextInt(2000).toLong())
    "Stop it!"
}

suspend fun selectInsult(john: ReceiveChannel<String>, mike: ReceiveChannel<String>,
                         adult: Deferred<String>) {
    select {
        // [..] the rest is like before
        adult.onAwait { value ->
            println("Exasperated adult says '$value'")
        }
    }
}

fun main(args: Array<String>) {
    runBlocking {
        val john = john()
        val mike = mike()
        val adult = adult()
        repeat(6) {
            selectInsult(john, mike, adult)
        }
    }

Notice that you should be wary of mixing the two kinds of clauses. That is because the result of onAwait is always there. So in our example, after it fires the first time the adult takes over and keep shouting Stop it! whenever the function selectInsult is called. Of course in real usage you would probably make the select expression returns a result to check for the firing of the onAwait clause and end the cycle when it fired the first time.

Summary

With this article we have seen what are coroutines and what they bring to Kotlin. We have also shown how to use the main functionalities provided around them and exploit their potential to make your asynchronous easier to write. Writing asynchronous software is hard, this library solves for you the most common problems. However we have just scratched the surface of what you can do with coroutines.

For example, we have not talked about all the low-level features for creators of libraries. That is because we choose to concentrate on the knowledge that will be useful to most people. However if you want to know more you can read the ample documentation on kotlin.coroutines and kotlinx.coroutines. You will also find a reference for the module and a deep guide on how to apply coroutines on UI (both Android and Desktop).

Building Languages using Kotlin - KotlinConf

Building Languages using Kotlin – KotlinConf

I attended KotlinConf to give a presentation about Building Languages using Kotlin. It was an amazing experience. The organization was great, and the whole experience increased my enthusiasm towards Kotlin: I thought it was not possible and I was proved wrong.

It was very nice to meet not only other Kotlin enthusiasts but also a lot of developers from JetBrains. I am in awe of what that company is doing with Kotlin, with their IDEs and with Jetbrains MPS.

While you can read online statistics about growing Kotlin adoption is very different to meet people from top companies, coming from all around the world, eager to listen what is new about Kotlin. You really feel that the Kotlin community is growing.

I was mind blowed by the first keynote: the support for multi-platform Kotlin projects is awesome. Imagine writing modules that you can share in applications across the JVM, Android, iOS application and the browser. Isn’t it incredible? Well, get used to it, because it is here, it is real and it will have an impact on our lifes as developers. For details take a look at the KotlinConf Keynote Recap and if you cannot believe me take a look at the official app of the conference with modules running on the server, the browser, Android, and iOS.

Below there is the video of my presentation and here you can find the slides.

Building Languages using Kotlin – Code

You can get the code and subscribe to receive news from SuperKotlin.

Java as your Kotlin Study Buddy

Java as your Kotlin Study Buddy

Switching to a new primary language can be daunting. We know the ins and outs of the language we have been working with for years, and all the sudden we’re newbies again. While this is always a good exercise to put yourself in, and comes with lots of learning, there is also a bit of vulnerability. If your primary language has been Java, and you’re making the switch to Kotlin, you might be feeling a bit of this insecurity.

You’re in luck in this case. The knowledge you have of Java is in no way obsolete.

Kotlin is a language that runs on the Java Virtual Machine, with the same bytecode that is at the core of the Java we know. So there is a question you should ask:

How can we take advantage of this?

Because Kotlin compiles down to bytecode, we can decompile that bytecode into the equivalent Java. My favorite tool to do this is the Kotlin Bytecode Viewer right in Android Studio and IntelliJ IDEA. I like always having it right there in my IDE.

Other options include the ClassyShark Bytecode viewer, or Luyten. By using one of these latter options, you are able to view the decompiled Java from class files where you may not have the source. You can also compare results from different decompilers.

How can this be useful to you? Let’s say you come across this snippet of code:

val (phoneNumber, address) = friend.contactInfo

You know you have a friend object, and Friend has a contactInfo property. That property is a ContactInfo object that has a phone number and an address.

data class ContactInfo(val phoneNumber: String, val address: String)

What’s weird here is that we’re assigning the value of contactInfo to val (phoneNumber,eNumber, address).

This is not the Java I know. We can decompile the bytecode for this Kotlin to get a better sense of what exactly is going on.

ContactInfo var3 = friend.getContactInfo();
String phoneNumber = var3.component1();
String address = var3.component2();
var3 = null;

This Java clears a bit of this up.

What this is doing is getting the contact information from the friend object, then getting the phoneNumber and address from there. Not bad.

We can find out more about these numbered component methods by decompiling the ContactInfo data class.

public final class ContactInfo {
  @NotNull
  private final String phoneNumber;
  @NotNull
  private final String address;

  @NotNull
  public final String getPhoneNumber() {
     return this.phoneNumber;
  }

  @NotNull
  public final String getAddress() {
     return this.address;
  }

  public ContactInfo(@NotNull String phoneNumber, @NotNull String address) {
     Intrinsics.checkParameterIsNotNull(phoneNumber, "phoneNumber");
     Intrinsics.checkParameterIsNotNull(address, "address");
     super();
     this.phoneNumber = phoneNumber;
     this.address = address;
  }

  @NotNull
  public final String component1() {
     return this.phoneNumber;
  }

  @NotNull
  public final String component2() {
     return this.address;
  }

  @NotNull
  public final ContactInfo copy(@NotNull String phoneNumber, @NotNull String address) {
     Intrinsics.checkParameterIsNotNull(phoneNumber, "phoneNumber");
     Intrinsics.checkParameterIsNotNull(address, "address");
     return new ContactInfo(phoneNumber, address);
  }

  // $FF: synthetic method
  // $FF: bridge method
  @NotNull
  public static ContactInfo copy$default(ContactInfo var0, String var1, String var2, int var3, Object var4) {
     if((var3 & 1) != 0) {
        var1 = var0.phoneNumber;
     }

     if((var3 & 2) != 0) {
        var2 = var0.address;
     }

     return var0.copy(var1, var2);
  }

  public String toString() {
     return "ContactInfo(phoneNumber=" + this.phoneNumber + ", address=" + this.address + ")";
  }

  public int hashCode() {
     return (this.phoneNumber != null?this.phoneNumber.hashCode():0) * 31 + (this.address != null?this.address.hashCode():0);
  }

  public boolean equals(Object var1) {
     if(this != var1) {
        if(var1 instanceof ContactInfo) {
           ContactInfo var2 = (ContactInfo)var1;
           if(Intrinsics.areEqual(this.phoneNumber, var2.phoneNumber) && Intrinsics.areEqual(this.address, var2.address)) {
              return true;
           }
        }

        return false;
     } else {
        return true;
     }
  }
}

Looking specifically at those ordered component methods, we see that they return the phoneNumber, and address fields, in order.

@NotNull
public final String component1() {
  return this.phoneNumber;
}

@NotNull
public final String component2() {
  return this.address;
}

When we have a data class, we automatically get these ordered components for destructuring class declarations. This is what we were seeing in that first snippet of code we decided to evaluate. Because data classes are so simple to create, this feature can be used in many places. You can use it to return multiple related values from a function, and to iterate through a map.

for ((phoneNumber, address) in addressBook) {
 // Do something with phoneNumber and address
}

Summary

Learning a new language is fun, and we can make it less of a hurdle by applying the knowledge we already do have. This was one example of how we can use our knowledge of Java to get to know some unfamiliar Kotlin code. Try it yourself next time you run into something you wish you  knew more about!

Victoria was drawn to programming because of its potential to help people in a meaningful way. She is currently a Software Developer at Collective Idea, building mobile and web applications. The conferences she has spoken at have been an enjoyable way to connect with the technical community, and exchange information with others. In her spare time, Victoria enjoys dancing, and curling up with a good book.

You can follow her on Twitter or visit her website website at victoriagonda.com

Review Of Kotlin For Android Developers

Review Of the Book Kotlin For Android Developers

This is a review of the book Kotlin For Android Developers by Antonio Leiva, an Android Engineer working for an international company.

When you have to pick an educational book the first thing you have to understand is:

  1. what kind of book is
  2. whose the book is for

When it comes to books aimed to teach a new programming language they can roughly divided in two groups: theoretical and pragmatic ones. A theoretical book can be a 1000+ page book that teach all the aspects of the language, from the platform to each construct, usually in a logic order of ascending difficulty. Instead a pragmatic book teaches a language explaining the concepts, while you meet them in the course of building something, like an app.

A book may be too short or change arguments too quickly for a beginner audience or, vice versa, it might have a too slow pace for an advanced user. Granted, some books are just bad, but usually the problem is that the reader picked the wrong book.

Audience Of The Book

The title itself of the book Kotlin For Android Developers does a good job in clarifying its type and audience: it is a pragmatic book for experienced Android developers that want to pick up Kotlin. Which means that it builds upon your Android knowledge to teach you how to do with Kotlin the stuff you already know to do with Java.

To put in another way: the book does not explain how to create Android applications, if you do not already know how to do that. In fact, if you are not an experienced Android developer, you will not understand what is going on or why somethings matters. Probably you will not even understand Kotlin that well.

This also means something that might be obvious to some, but not all: there is very little theory. You should already know how the tools work (e.g., Gradle) and what things like delegates or lambda are. Only the chapter on Generics explains a bit of the theory behind them. Also, typically the issues with using a certain feature are not discussed, unless the issue is related to the Kotlin approach.

For instance, when listing the operators that you can overload that is what the book has to say about identity comparison in Kotlin:

Operators === and !== do identity checks (they are == and != in Java respectively)
and can’t be overloaded.

─ Chapter 11, p. 49

In short, if you an expert programmer that complains constantly about filler content, you are the perfect audience for this book. If you are a novice that needs hand-holding you should look elsewhere and maybe come back later to this book, once you have covered your basis.

Structure Of The Book

The book does not really have a formal structure, for the most part: there are 30 short chapters about several aspects you will encounter developing an Android app. An Android developer might notice that the order of the chapters resembles how a real app is developed: you create a working app as soon as possible and then you refactor it to make it beautiful.

Although to be fair most of the time the chapters does not seem to follow any particular order. We cannot really understand if there is any reason to explain control flow expressions in chapter 22 of 30. On the other hand, given the audience of the book, this is not really a problem because you are supposed to already know your way around an Android app.

In our opinion, this approach makes sense given the audience (developers with experience on Android). Busy developers can jump quickly to the point they are interest into, while skipping parts that are not extremely important for them right now. Experts do not need someone to draw the path for them, they need pointers to find quickly the information they are looking for.

There are only a few minor issues related to the order of topics. For example, reified generics are discusses before the chapter on generics; the REPL and the online playground are not mentioned in the Getting ready chapter, but in the introduction of the chapter about classes.

The internal structure of each chapter is more consistent: there is usually a problem and the code that solve it, all related to a weather app that is used throughout the book. The code of each chapter is presented in its entirety in the companion repository of the book. The reader is constantly reminded of the repository. Also, frequently the author note that the chapter only discuss the major modifications to the code and not everything that is in the repository. We think that code should be at the center of books about programming, so we really liked this approach.

There are a few chapters that just list, or explain, things about Kotlin, without any reference to the app. For example, chapter 11, that lists which operators you can overload, or chapter 18, that lists collections and related operations of the Kotlin standard library.

Content Of The Book

The book covers all the main aspects of Kotlin: from variables and null safety to generics and lambdas. So there is no complain to be made there. They are also covered in pragmatic terms, you are rarely going to see a few pages without any code. When this happens is usually because of the few things that needs an explanation, or a list, like the operators that you can overload. There is also a chapter for coroutines, an experimental features of Kotlin 1.1, which is a nice surprise. Of course, all the content is explained with Android development and issues in mind.

The book also covers a few essential libraries and tools: Anko and the Kotlin Android Extensions. Anko is a library composed of several modules and many of them are used in the book: Anko SQLite, Anko Coroutines, etc. The addition of this library, which will probably be used by almost all developers, is a good example of the benefits of the pragmatic approach of the book. You are going to learn most of what you are going to use in your everyday development for Android with Kotlin.

The only important thing that the book does not talk about is Anko Layouts. And the reason is that the author does not care about it, which is a perplexing choice or, at the very least, a perplexing justification.

Anko is a powerful library developed by JetBrains. Its main purpose is the generation of UI layouts by using code instead of XML. This is an interesting feature I recommend you to try, but I won’t be using it in this project. To me (probably due to years of experience writing UIs) using XML is much easier, but you could like this approach.

─ Chapter 7, p. 33

Maybe it is true that most Android developers are used to XML, just like author, but it seems an odd reason to exclude something, especially since the author itself present it as the main purpose of the library.

In any case, with this choice the author miss the chance to talk about type-safe builders, which can be useful to build also HTML layouts or any kind of type-safe hierarchical data.

Summary

Once you understand the audience of the book you are going to agree that it has only a few flaws. The content you need is all there, although you could argue that some chapters devoted to theory are a bit thin.

For instance, the first chapter, that explains why you should use Kotlin for Android is a bit short. It does not really introduce all the good things of Kotlin (e.g., Anko) that the book will talk about, and it does not present well the one it mentions (e.g. Expressiveness shows only data classes and not other features linked to expressiveness). But this is mostly nitpicking.

The structure of the book can be perplexing. However, since the book is for experienced Android developers, this might be annoying for some, but not problematic for the target audience.

On the other hand if you know Android and prefer a pragmatic and code-first approach this book is the best you can find to learn Kotlin to use it for your Android apps.

There is no filler content, not a word more than the one you need to get you going and there is no quicker way to learn how to use Kotlin in your job.

A nice touch is that the author periodically updates the book, also based on the feedback he receives. The updates are sent automatically for the digital version. Buyers of the physical one can ask the author for free access to an updated digital edition.

Disclaimer: the author gave us a copy of the book for the review but we do not have any agreement for affiliate marketing or any other interest in recommending this book.

Kotlin Courses

Kotlin Courses: Reviews And Comparison

You have seen the benefits Kotlin can bring to you, however you have to learn Kotlin. You can do learn it on your own, pick a book or get access to a course.

The problem is to you have to figure out which course is best for you: we have reviewed the most relevant ones and in this article we are going to give you the information you need to pick the course that is right for you.

If none of this course is what you are looking for you can still look into our list of 100+ Resources To Learn Kotlin The Right Way.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


What you will find in this article?

First of all you will find the review of the courses, divided in four groups. Depending on the level at which you want to learn Kotlin, your background and if you are interested specifically for Android development you can pick one or more specific groups to investigate them further.

The following table provides a summary of the characteristics of the available courses.

Name Platform Type Length Price ($)
Kotlin for Java Developers Treehouse Introductory 02:41 25-49 (subscription)
Learning Kotlin for Android Development Lynda.com Introductory 01:01 15-25 (subscription)
Introduction to Kotlin Programming / Advanced Kotlin Programming Safari (O’Reilly) Course for developers 05:14 / 03:00 39 (subscription)
Introduction To Kotlin Udemy Course for developers 04:55 50
Kotlin Fundamentals Pluralsight Course for developers 04:47 29 (subscription)
Kotlin for Beginners: Learn Programming With Kotlin Udemy Course for non-developers 06:37 95
The Essential Kotlin Programming Course (Android Developers) Udemy Course for non-developers 25:25 150
The Complete Kotlin Developer Course: Become A Pro! Udemy Course for non-developers 04:04 30
Kotlin & Android Developer Masterclass – Beginner to Advanced Udemy Course for Android 19:43 200
The Complete Android Kotlin Developer Udemy Course for Android 26:27 200

Notes: if the price indicate a subscription it is a monthly subscription to a whole library of courses including the one reviewed; Udemy pricing varies wildly and can be lowered even by 90% during promotions; the length of a course could vary since it can be updated.

Beside helping you picking up the right course for you we have a few more considerations to share:

Introductory Courses

A stilyzed representation of programming

Kotlin for Java Developers is a relatively short journey (it lasts 161 minutes) to learn the basics of Kotlin through the development of card games for Android. The course is meant to introduce Android developers to Kotlin and help them get started or evaluate the adoption of Kotlin in their professional life.

Learning Kotlin for Android Development is a short one-hour course for learning the basics of Kotlin and exploring how it can help in your Android development, all by creating a simple app for Android. It also touches on the setup of Android development (eg. creating an emulator) and converting a Java app in Kotlin.

Courses For (Java) Developers

A cup, usually a symbol of Java, with a Kotlin logo

These are course for developers, especially experienced Java programmers. They can be basics or in-depth, but usually takes advantage of previous Java knowledge to skip most of the theory.

Kotlin Programming By O’Reilly

Introduction to Kotlin Programming and Advanced Kotlin Programming are two O’Reilly courses from Hadi Hariri, VP of Developer Advocacy at JetBrains, the company that created Kotlin. The courses do not strictly require a knowledge of Java, in the first one there is even short introduction to the JVM. Having said that, there is one part dedicated to the interoperability with Java, so if you know Java or any other JVM language you are going to get the most out of it.

In any case you need to be a developer. The course covers well how to do things in Kotlin, but not the theory behind the features. The first course covers the basics, that you will use in your everyday job: everything from conditional expressions to the fundamentals of Kotlin lambdas. The second one covers advanced topics like metaprogramming, delegation  and deeper examination of Generics and Functions.

Introduction To Kotlin

Despite the name, Introduction to Kotlin it is a relatively in-depth (5 hours) course to explain Kotlin to Java developers. Technically the overview says only that Java knowledge is beneficial, but there are comparison to Java here and there. Furthermore many reviews laments a very fast pace, so probably Java experience is needed to have the best experience.

The course is essentially divided in two parts: the first covers Kotlin syntax and how to use all its features, even higher-order functions; the second one is about the advanced usage of Kotlin collections and reflection.

The second part seems a bit rushed, I mean there is even a section titled Odds & Ends. On the other hand the section on the usage of the Collections functions of the standard library can be quite useful especially if you come form Java and you have never used a language like C# (with LINQ).

Kotlin Fundamentals

Kotlin Fundamentals is a good course for experienced Java developers with a puzzling title. In fact the course explore all you need to know in your professional life to use of Kotlin in the best way, especially interacting with Java. For instance there is a few sections on how functional interfaces and nullability of Kotlin interact with Java. A more apt title would have been something like Real Life Kotlin For Java Developers.

Having said that, the course offers brief introduction to the topic at hand before developing it. It also focuses on pragmatic problems with can be useful for professional developers and, of course, puzzling for beginners. For instance, there is a section titled Working with Infinite Collections that explains Sequences in Kotlin, an expert would know why it makes sense to care about the issue, while a beginner would ask himself what infinite means.

Kotlin Courses For Non-Developers

A clueless person in a lab coat typing on an old computer

These are course for complete beginners in programming, you should expect and hope for a lot of theory.

Kotlin For Beginners: Learn Programming With Kotlin

Kotlin for Beginners: Learn Programming With Kotlin (see note) is a course to learn programming with Kotlin starting from scratch. And with that we mean that really you do not need to know anything even about Udemy, the platform the course uses. In fact there is an introductory video to explain the features of Udemy itself (eg. how to speed-up the video, where to find the companion resources, etc.) and how to best take advantage of the course. You cannot get more beginner friendly than that.

The course will teach you both the basic features and concepts of programming, in general, and the Kotlin language, in particular. Concepts and Kotlin idioms are explained together, for instance the difference between expression and statement is explained while explaining the advanced usage of if and when. However there are also theoretical sections, for example one on binary and hexadecimal numbers.

There are quizzes and coding challenges (i.e. exercises) to help your test and practice your programming skills. The course also offers solutions accessible through GitHub. It is a nice touch and a good way to introduce a professional tool to beginners.

In terms of content, apart from the obvious basics (e.g. variables, lists, etc.), there are a few sections that covers all aspects of object-oriented programming, everything from what methods are to singletons. Both theory (eg. information hiding) and practice are explained. It is important to note that you will not find explanation of the more advanced functional features of Kotlin, such as lambdas and higher order functions.

We would like to thank the author of this course for having given us free access to it. He has also prepared a special offer for our readers, following that link you will get the course for a reduced price.

There is no affiliate marketing agreement between SuperKotlin and the author or Udemy. That is to say we do not receive any money if you purchase the course with a discount or to show you this review or for anything else.

The Essential Kotlin Programming Course (Android Developers)

The Essential Kotlin Programming Course (Android Developers) is a very in-depth course (25 hours) that explains at length the topic at hand and then also explains how it works in Kotlin. Let’s say that there is one hour introductory section that explains the features of Kotlin and what are object oriented and functional programming.

The rest of the course is equally thorough in explaining the theory and how it applies to Kotlin programming. For instance it takes its time (2 hours) to explains Kotlin Collections of the standard library: what they are, the different functions, how they relate to the corresponding Java collections…

The course is both theory and practice, not just because it explain how doing things in Kotlin, but also because there are five hours of exercise lessons. In short this course is the closest equivalent to a traditional university course. Which is great if you think that online courses tend to be too quick and pragmatic, leaving out how things works and why they work that way.

The course lacks parts about Concurrency and Metaprogramming, that are still in the works. The course explains how to use programming tools (ie. IDEs) and in particular Android Studio (including the Emulator), but apart from that there seems to be little on the specifics of Android development.

The Complete Kotlin Developer Course: Become A Pro!

The Complete Kotlin Developer Course: Become A Pro! is a good course for beginners that overpromise a bit. We mean that the course is short (4 hours) for a complete course intended to transform a beginner in a professional developer. It basically covers the basics of programming and the syntax of Kotlin: from variables to what is object oriented programming.

The course is cheap and short for a complete course, so in some sense it is the opposite of some other complete courses, but it is also very popular, so many people find it worthwhile. If you want to quickly and cheaply learn programming and understand that the course does not actually prepare you to become a professional, it can be a good choice.

Courses For Non-Developers Interested In Android

Audience cheering for the announcement of Kotlin support on Android

These are course for people that do not know anything about programming except that they want to create mobile apps for Android, probably for making money with apps.

Kotlin & Android Developer Masterclass – Beginner to Advanced

Kotlin & Android Developer Masterclass – Beginner to Advanced is a comprehensive course (19 hours) that teaches Kotlin in the context of Android development. The course is essentially divided in two parts: the first explains the basics of programming with Kotlin (eg. variables, functions, etc.), the second one covers Android development, everything from using Android Studio to user interfaces, databases and web services.

When it comes to content the only topic that is not explained explicitly are functional features of Kotlin, although some of them are used in practice, for instance when talking about listeners. This is not a big oversight if you only care about Android development, but it matters if you are more interested in a comprehensive Kotlin programming course.

The course could probably use an editor to review the texts for style and clarity, for instance the title of the lessons are unnecessarily complex at times and do not follow a coherent style. The actual lesson videos follow an understandable script. The organization of the course is also a bit perplexing, for example: a lesson to explain return types of functions is inside a section dedicated to object oriented programming; arrays are explained after advanced objected oriented programming.

The Complete Android Kotlin Developer

The Complete Android Kotlin Developer is a very in-depth course (26 hours) to learn programming and Android development using Kotlin. It touches so many topics that we cannot really cover them all, but in short we can say:

  • it starts by covering the basics of programming, both in theory and with Kotlin, with things such as conditional expressions up to object oriented programming
  • it continues with many example Android apps that are used to explain interaction and different layouts available in Android
  • it passes to advanced Android apps to shows how to use important programming tools like databases (SQLite and Firebase), web services and specific Android features like sensors and media player
  • it ends with complete example apps to put everything together

It is one of the longest, most expensive and most followed course for Kotlin on Udemy. It is designed to transform a normal person in a professional junior Android developer. Which means that many people want to become professional developers and they find this course good for their needs. The downside of covering so many topics is that many reviewers mentions that the rapid switch from one topics to the next can leave some people hanging. So keep that in mind.

The only thing that does not cover well is making mobile games. We think that is for the best because to cover the subject professionally it would require a whole new in-depth course and Kotlin might not be the best choice for that kind of apps. However it is relevant to note it for complete beginners.

When To Pick A Book, An Online Course Or In-person Training

There are four main different approaches that you could decide to take to learn a programming language:

  1. To learn on your own: using only free online resources and building your custom learning program
  2. To buy a book and follow it
  3. To get access to an online course, follow the lessons and do the exercises
  4. To attend in-person training

The option number zero does not require any monetary investment, however it is the one that requires the most time and pose the most risks, because the person could miss important subjects or using sub-optimal resources. We have already linked our list of resources to help you if you want pick this way, so let’s focus on the other three instead.

These three options offer different balance on different aspects.

  • The risk: the more supervision you have, the more you can be reassured of being on the right track, your errors can be caught sooner.
  • Time to learn: the less supervision you will get, the more you will rely on trial-and-error. It means it will take longer to really master the content.
  • Investment: the investment in term of money grows significantly with the level of supervision. A book can cost tens of euros/dollars, a MOOC could go from the tens to the hundreds of euros/dollars, while in person training will typically be in the thousands of euros/dollars
  • Access: buying books and access to MOOCs is very easy. Once you got access you can read a book everywhere, while typically you will consume a MOOC at your desk, ready to work on exercises. In person training instead requires to hire a teacher and agree on a date to deliver the course, so access is less immediate to get
Kotlin courses vs in person training vs book

Book vs MOOC vs In-person training

So what is the best solution for you to learn Kotlin?

It really depends on the value of your time and the amount of money you can afford to invest.

If you are a student with the head full of dreams and an empty wallet the answer is clear: you should just use free online resources or maybe buy a book for 20-30$. That would be a wise investment. After all, if it takes a few more months to learn Kotlin it will not make a huge difference for you.

As a freelancer or a young professional probably a MOOC is the best compromise: you get lessons from knowledgeable teachers and you typically get exercises to evaluate your progress. MOOC are also usually updated more frequently than books, so you get fresher content, in line with the evolution of Kotlin. Maybe there is also a forum where you can get answers to a few of your questions.

If you are a seasoned professional or you work at a company with an healthy business than in-person training could be the most reasonable choice for you. You cannot afford to learn by trial-and-error, you do not have the time to look for the best resources online and evaluate them. Taking a few months to learn Kotlin would have an impact on the business as projects are delayed or move on slowly. Considering the cost of an employee for a company your time is extremely expensive. Whatever can save you time justify significant investments in terms of money.

So depending on where you are in life, you can value different things and different ways to learn could make more sense for you.

Books For Self-Learners

Historically the favorite tool for learners has been a book, or many books. It is a tool that can be used both by self-learners and students in a regular course or learning institution. The advantage of learning on your own is that you can choose your own pace and pay less than a traditional course, since a book cost much less than a teacher.

The disadvantage is the lack of a person that can help you understand the material, the loneliness of the experience and the static nature of a book. A static nature means that the information can become outdated and it is always in the same form and the same pacing: a written text with a lot of repetitions to insure everybody can understand.

Learning Online: MOOC

A new tool was created and delivered through the internet that could overcome some of the limits of books: MOOC (Massive Open Online Courses). While there is not a rigid formula behind a MOOC, they usually share a few characteristics:

  • different types of videos (lessons, lectures, etc.) and content (exercises, references, etc.)
  • a minimal structure in the learning material
  • permanent access to content that is regularly updated
  • a learning community
  • a teacher available to help through asynchronous methods of communication

The learner must still be willing to put the effort and to learn the material mostly on its own. But if he encounters some problem the community or the teacher can help and they can always provide support and motivation to learn. The content is better organized, provided in different forms. For instance you can have video, test quizzes and even a short reference document. It is also usually updated regularly.

The downside of a video course is that the material is harder to search and access and the cost is higher. It is harder to search and access because it is a video and not a text, so neither humans nor software can quickly scan it. It cost more because it is more expensive to produce and a teacher is usually available to help students.

In-person Training For Learning Kotlin

A lot of devices

Apart from a few cases, usually a business need a tool that can give a definitive time frame for getting the results it needs. That is because planning is fundamental in a business: if a project must be started now, delaying it because the personnel does not have the right skills is going to cost lost revenues.

Preferably it should also be a tool that can save time by being adaptable to the specific needs of the business. There is no need to teach your developers how to make Android application in Kotlin, if you do not plan to create them. Also, a course should be based on the specific background of your personnel.

In the case of learning that tool is a traditional face-to-face course delivered by a teacher, that has experience in the subject and in teaching to professionals. We can provide that: we have courses designed for professional developers and technicians or scientists. Our courses can prepare both Java and non-Java developers to create professional software in idiomatic Kotlin. We can also teach scientists, and all other kinds of technical personnel, scripting and basic programming in Kotlin. If you are interested look at our page for Courses.

Summary

There are may ways to learn depending on where you are in life, how valuable is your time and how you prefer to learn. Online courses are a good options for many of you and we hope that this article will help you pick the right one for you. Whatever way you choose we hope you are going to learn Kotlin soon and have fun doing it.

We are not connected to any author or platform of these courses. We do not have any affiliate marketing agreement with them and we are not getting anything to review any of them.

Compile Kotlin to native executables: hands on experience

Kotlin is becoming the one language you can use in every context:

  • it can be compiled to JVM bytecode and reuse JVM libraries
  • it can be transpiled to JavaScript and use JavaScript libraries
  • it can now also be compiled to native code reusing native libraries

While the JVM and JavaScript target are already mature, the native target is more recent and it is still experimental. However we decided to take a look and check ourselves what is already possible to do.

We are working with version 0.3 which supports:

  • Mac OS X 10.11 and later (x86-64), host and target
  • Ubuntu Linux x86-64 (14.04, 16.04 and later), host and target
  • Microsoft Windows x86-64 (tested on Windows 7 and Windows 10), host and target
  • Apple iOS (arm64), cross-compiled on MacOS X host
  • Android arm32 and arm64,cross-compiled on Linux or MacOS X host
  • Raspberry Pi, cross-compiled on Linux host

In other words you can target all the 3 main OS for the Desktop, the 2 main OS for mobile, and Raspberry Pi.

What we are going to do

Our goal is to check in practice how we can use Kotlin native today. We are going to build a simple application using a C library (libpng).

We are going to build an application that generates a simple image: the Kotlin logo. Our program will take as input the desired size of the image and generate the logo. The logo will be saved in PNG format, and that is why we need to use libpng.

We are going to see:

  1. How to configure the project using a specific gradle plugin
  2. How to build the Kotlin library manually
  3. How to launch the compiler manually
  4. How to write the code

Setup the project using the kotlin native gradle plugin

The simplest way to build a project using Kotlin native is to use gradle as your build system and the corresponding plugin.

To get started you need to:

  • create gradle.properties
  • create build.gradle
  • create the src/main/kotlin directory for your Kotlin source code
  • typically you want also to run gradle wrapper. Basically it creates a little script that install gradle if needed. Read more here.

Let’s see what we need to insert in those you files.

gradle.properties

konan.version=0.3

We specify just the version of the kotlin native compiler we want to use.

build.gradle

buildscript {
    repositories {
       mavenCentral()
       maven {
           url  "https://dl.bintray.com/jetbrains/kotlin-native-dependencies"
       }
   }

   dependencies {
       classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:0.3"
   }
}

apply plugin: 'konan'
apply plugin: 'idea'

konanArtifacts {
    LogoGenMacbook {
        target "macbook"
    }
}

In this case the gradle script contains also the IDEA plugin so that we can generate an IDEA project by running ./gradlew idea.
We have then defined a target to build the executable for macos. You could want to pick another target. Valid targets currently are:

  • android_arm32
  • android_arm64
  • iphone
  • iphone_sim
  • macbook (for macOS)
  • mingw (for Windows)
  • linux

Hello world from native

src/main/kotlin/logogen.kt

fun main(args: Array<String>) {
   println("Hello from native!")
}

At this point we can compile everything with ./gradlew build. Then we can just run ./build/konan/bin/LogoGenMacbook.kexe to execute it and voila!

Using native libraries

While printing on the screen can be exciting at first after a while we could want to move forward. For doing anything meaningful we are going to need some native library. In this example we are going to use libpng, but the same procedure applies to use any library.

Note that you can reuse all native libraries that follows the C ABI. For other languages like C++ or Rust you could have to wrap the libraries with C before being able to use them, or use existing C bindings, where available.

Install native library

First of all we could want to install the library on our system. This is technically not needed: we could just download it somewhere and specify the include directory and the linker options.

On mac I ran:

brew install libpng

Define def files

Now we need to make Kotlin code aware of the C functions we want to use from libpng. To do that we just list the header files we want to use.

src/main/c_interop/png.def

headers = /usr/local/include/png.h stdio.h stdlib.h string.h math.h

You could notice that we included both headers from libpng and others from the standard library. Now, we could be tempted to define another def file for the standard library but that did not work for me. Why? Because when importing png.h the compiler also imports all files included by png.h, including some from the standard library. For the corresponding structures (like FILE), it creates a Kotlin wrapper. So we end up with two different FILE: one from the standard library and one for png, that was imported implicitly. This cause all sort of compilation errors, so let’s make our life easier. This is something that will need to be sorted out eventually, but for now let’s use a workaround and define one def file with everything we need.

Add linking instructions

We need also to update build.gradle to use our library:

// This is new
konanInterop {
   png {
       defFile 'src/main/c_interop/png.def'
   }
}

konanArtifacts {
    LogoGenMacbook { 
        linkerOpts "-L/usr/local/lib -lpng" // we added this line
        target "macbook"
        useInterop 'png' // and this one
    }
}

Import

Now we need to import the C functions and structures in our Kotlin file. We do this with this line:

import png.*

And that is it, we are now ready to use libpng from Kotlin!

What our application will do: logos, logos of all sizes!

Our application is going to generate the Kotlin logo of the size we want.

You can download the Kotlin logo from the official website but our program will instead generate it programmatically and save it to a PNG image.

Let’s draw our first image

Let’s start with a first version that will generate a logo of 500×500 pixels. It will generate the logo using three bands of homegenous color. We will add the nice gradient of the real logo in a successive iteration.

import kotlinx.cinterop.*
import png.*

val PNG_LIBPNG_VER_STRING = "1.6.29"
val PNG_INTERLACE_NONE = 0
val PNG_COMPRESSION_TYPE_BASE = 0
val PNG_FILTER_TYPE_BASE = 0

data class Color(val r: Int, val g: Int, val b: Int)

val ORANGE = Color(244, 133, 25)
val BLUE = Color(39, 137, 217)
val WHITE = Color(255, 255, 255)

fun setRGB(rowBuffer: CPointer<ByteVar>, y: Int, x: Int, color: Color) {
     rowBuffer.plus(3 * x + 0)!!.reinterpret<ShortVar>(()[0] = color.r.toShort()
     rowBuffer.plus(3 * x + 1)!!.reinterpret<ShortVar>(()[0] = color.g.toShort()
     rowBuffer.plus(3 * x + 2)!!.reinterpret<ShortVar>(t()[0] = color.b.toShort()	
}

fun draw_logo(width: Int, height: Int, filename: String) {
   val fp = fopen(filename, "wb")
   if (fp == null) {
      println("Unable to open the file")
      return
   }

   val png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, null, null, null)
   if (png_ptr == null) {
      println("Unable to create the png (png_create_write_struct failure)")
      return
   }

   val info_ptr = png_create_info_struct(png_ptr)
   if (info_ptr == null) {
      println("Unable to create the png (png_create_info_struct failure")
      return
   }

   png_init_io(png_ptr as CPointer<png_struct>, fp)

   val bit_depth = 8
   val color_type = PNG_COLOR_TYPE_RGB

   png_set_IHDR(png_ptr, info_ptr, width, height,
         bit_depth, color_type, PNG_INTERLACE_NONE,
         PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE)

   png_write_info(png_ptr, info_ptr)

   val rowBuffer = nativeHeap.allocArray<ByteVar>(3 * width + 3)
   for (y in 0..(height-1)) {
      val yProp = (y+1).toFloat()/height
      for (x in 0..(width-1)) {
         val xProp = (x+1).toFloat()/width
         val topBand = yProp <= 0.5 && xProp <= (0.5 - yProp)
         val middleBand = !topBand && xProp <= (1.0 - yProp)
         val lowerBand = yProp >= 0.5 && ((xProp <= 0.5 && xProp>= (1.0-yProp)) || (xProp>=0.5 && xProp <= yProp))
         if (topBand || lowerBand) {
            setRGB(rowBuffer, y, x, BLUE)
         } else if (middleBand) {
            setRGB(rowBuffer, y, x, ORANGE)
         } else {
            setRGB(rowBuffer, y, x, WHITE)
         }
      }
      png_write_row(png_ptr, rowBuffer)
   }

   png_write_end(png_ptr, null)

   fclose(fp)
   println("Logo of size $width x $height generated in $filename")
}

fun main(args: Array<String>) {
   draw_logo(500, 500, "logo.png")
}

We have a bunch of calls to libpng functions. You can look at the documentation of that library if you are interested in details, we will mostly comment the Kotlin stuff.

Our main contains just a call to draw_logo. This function is where we create a PNG and save it to file. Most of the code is just boilerplate. The interesting part is composed by the two annidated loops over the height and the width of the image. Basically for each pixel we want to calculate its proportional position (xProp, yProp). These are values from 0 and 1, where 0 for the xProp indicates the left, 1 indicates the right and 0.5 indicates the middle. Similarly for yProp 0 indicates the top, 1 the bottom and 0.5 the middle. For each pixel we want to understand in which band it belongs. Take a look at this picture:

You can compare the picture with the expressions to calculate to which band a pixel belong:

val topBand = yProp <= 0.5 && xProp <= (0.5 - yProp)
val middleBand = !topBand && xProp <= (1.0 - yProp)
val lowerBand = yProp >= 0.5 && ((xProp <= 0.5 && xProp>= (1.0-yProp)) || (xProp>=0.5 && xProp <= yProp))

Once we have figure out the band we just paint the pixel with the color used for that band: BLUE for the top and lower band, ORANGE for the middle one, and WHITE if the pixel does not belong to any band.

To set the single pixels we use the setRGB function. In this function we receive an array of bytes (rowBuffer). Now, it contains a sequence of pixels, one after the other. For each pixel it contains the red, green, and blue components. We calculate the position of the component of interest for the pixel of interest. For example, for the red component we use rowBuffer.plus(3 * x + 0). Ok, this is where we want to write the value of the red component. However there is an issue because we cannot use a byte, given it is a signed value in Kotlin, so it can hold values between -128 and 127, while we have values between 0 and 255. So we use a short instead. We cast the byte array to a short array and we write the first element. Note that in this way we override the next pixel, so calls to setRGB need to be executed in order. Support for unsigned values is one of the issues that needs to be sorted out.

Consider program arguments

The next step is to consider the program arguments. We expect the user to tell us the size of the logo he or she wants.

val MAX_SIZE = 2000

fun main(args: Array<String>) {
   if (args.size != 2) {
      println("2 arguments expected, while we received ${args.size}")
      return
   }
   val width = args[0].toIntOrNull()
   val height = args[1].toIntOrNull()
   if (width != null && height != null && width in 1..MAX_SIZE && height in 1..MAX_SIZE) {
      draw_logo(width, height, "logo_${width}x$height.png")
   } else {
      println("Please specify positive dimensions equal or lower than $MAX_SIZE")
      return
   }
}

We need to check that two values are provided and that both are valid. We accept only integers between 1 and 2000. If both are valid we move on with the generation. We also use the width and the height to determine the name of the image file.

And here there are our logos of all sizes:

Draw a gradient

Our logos look nice but the original is still nicer because it use a gradient, so the different bands are not homogeneous but the color changes as we move from across the band. Let’s try to replicate that.

We need first to add a bunch of elements:

data class Point(val x: Float, val y: Float) {
   fun distance(other: Point) = sqrt(pow((x - other.x).toDouble(), 2.0) + pow((y - other.y).toDouble(), 2.0))
}

data class ColorSource(val point: Point, val color: Color)

class Band(val colorSources: List<ColorSource>) {
   fun color(point: Point) : Color {
      val invDistances = colorSources.map { 1.0f/it.point.distance(point)}
      val sumInvDistances = invDistances.sum()
      var r : Double = 0.0
      var g : Double = 0.0
      var b : Double = 0.0
      colorSources.forEachIndexed { i, colorSource ->
         r += colorSource.color.r * (invDistances[i]/sumInvDistances)
         g += colorSource.color.g * (invDistances[i]/sumInvDistances)
         b += colorSource.color.b * (invDistances[i]/sumInvDistances)
      }
      return Color(r.toInt(), g.toInt(), b.toInt())
   }
}

val TOP_BAND = Band(listOf(
      ColorSource(Point(0.0f, 0.0f), Color(24, 141, 215)),
      ColorSource(Point(0.5f, 0.0f), Color(128, 110, 227)),
      ColorSource(Point(0.0f, 0.5f), Color(0, 149, 213))))

val MIDDLE_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.0f), Color(248, 137, 9)),
      ColorSource(Point(1.0f, 0.0f), Color(248, 137, 9)),
      ColorSource(Point(0.0f, 0.5f), Color(215, 103, 128)),
      ColorSource(Point(0.0f, 1.0f), Color(199, 87, 188))))

val LOWER_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.5f), Color(128, 110, 227)),
      ColorSource(Point(0.0f, 1.0f), Color(0, 149, 213)),
      ColorSource(Point(1.0f, 1.0f), Color(128, 110, 227))))


And then to modify how we calculate the color in the inner loop of our draw_logo function.

...
val band = when {
   topBand -> TOP_BAND
   middleBand -> MIDDLE_BAND
   lowerBand -> LOWER_BAND
   else -> null
}
val color = band?.color(Point(xProp, yProp)) ?: WHITE
setRGB(rowBuffer, y, x, color)
...

What we are doing here?

For each band we write down the colors of the extremes. You can see the extremes in this picture:

And these are their values:

val TOP_BAND = Band(listOf(
      ColorSource(Point(0.0f, 0.0f), Color(24, 141, 215)),   // T1
      ColorSource(Point(0.5f, 0.0f), Color(128, 110, 227)),  // T2
      ColorSource(Point(0.0f, 0.5f), Color(0, 149, 213))))   // T3

val MIDDLE_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.0f), Color(248, 137, 9)),    // M1
      ColorSource(Point(1.0f, 0.0f), Color(248, 137, 9)),    // M2
      ColorSource(Point(0.0f, 0.5f), Color(215, 103, 128)),  // M3
      ColorSource(Point(0.0f, 1.0f), Color(199, 87, 188))))  // M4

val LOWER_BAND = Band(listOf(
      ColorSource(Point(0.5f, 0.5f), Color(128, 110, 227)),  // L1
      ColorSource(Point(0.0f, 1.0f), Color(0, 149, 213)),    // L2
      ColorSource(Point(1.0f, 1.0f), Color(128, 110, 227)))) // L3

For each pixel we want to calculate the color depending on how close it is to one of the extremes. In practice we calculate the closeness as the inverse of the distance between each two points. For each pixel we calculate this inverse distance to all the extremes and the sum. Then we calculate the color as the pixel as a proportion considering the closeness and the color of each extreme. This is what we do in Band.color.

And this is what we get:

It is still not as cool as the original one but we are getting closer.

Building everything manually

In this article we have seen how to use the gradle plugin to compile things. However if you prefer to not use it you can also do everything without.

Build the native compiler locally

You may want to compile the native compiler yourself.

To do this you should first clone the repository:

git clone https://github.com/JetBrains/kotlin-native.git

Then you could build it with these two commands:

./gradlew dependencies:update
./gradlew dist

And here you go, now you have the bleeding edge version of the compiler to play with!

Build library manually

Kotlin native is experimenting with its own format for libraries. If you want you can generate a library by running this command:

cinterop -def src/main/c_interop/png.def -copt "$CFLAGS" -target macbook -o build/c_interop/png

Use the compiler manually

If you want to invoke the compiler manually this is how you can do that. Note that here we are using the library we compiled at the previous step:

konanc $COMPILER_ARGS -target macbook src/main/kotlin/logogen.kt -library build/c_interop/png -linkerOpts "-L/usr/local/lib -lpng" -o build/bin/logogen

Summary

Is Kotlin becoming the new solution for “write it once, run everywhere?”

This is a possibility, I think. There is code we need to execute on different platforms. I do not think we will get applications that run on different platforms like the web, iOS and Android because the interactions are different and the user expectations are different. However we need and will probably get common business logic, common libraries. Kotlin seems an interesting language to deliver that.

That said it is possible to build something today, with the Kotlin native compiler as it is but there is a big roadblock: the editor support.

We would like to thank Mario Zechner for his comments which helped improving the article.

Kotlin Javascript Target: Use Kotlin in the Browser

Kotlin Javascript Target: Use Kotlin in the Browser

This article is a tutorial and introduction to run Kotlin on the browser, by compiling Kotlin to JavaScript. We are going to see the simplest way to setup a project that use existing JavaScript libraries. We are also going to learn and use the awesome when expression of Kotlin. This expression is quite useful and a good example of the pragmatic approach of Kotlin. You will probably try to use it everywhere.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


How Kotlin Supports Multiple Environments

Some languages saves development costs relying on a existing intermediate language or platform. The language you write is compiled or transpiled to a different language. So the existing compiler and/or virtual machines can be reused. This is the approach that Kotlin adopts by running on the JVM, which in turns can run almost everywhere.

The problem is that there are also specific environments that cannot be supported by a virtual machine because of their constraints. Two examples are: the browser and embedded systems. To support development on the browser we have to use JavaScript. So if we do not want to write directly using JavaScript we still have to transpile to JavaScript because that is the only language available on the browser. Furthermore an incredible amount of effort has been spent to optimize JavaScript engines.

By transpiling Kotlin to JavaScript we can use it both for client and server web development (through Node.js).

Why Using Kotlin Instead of JavaScript

Given that the support for JavaScript is so widespread you may ask yourself why using Kotlin and not directly JavaScript for web development. The first advantage is that you can use Kotlin for everything. You can create a web service and desktop application targeting the JVM and the corresponding web client targeting JavaScript. The second one is that JavaScript is not a good language for developing large applications.

It is a well known problem that is also addressed by TypeScript, a language that also transpile to JavaScript whose motto is JavaScript that scales. An alternative to the better language approach is to use complex JavaScript frameworks like Ember.

Kotlin For JavaScript

The current implementation targets ECMAScript 5.1 but there are plans to eventually target ECMAScript 2015 also.

The Kotlin support for JavaScript is not skin deep, but is geared both to the language and the modules. The problems are with the tools and the inherent incompatibilities between languages with dynamic and static typing.

Kotlin include libraries to support the manipulation of the DOM elements and also graphical elements using WebGL. The Kotlin compiler can also create JavaScript modules compatible with different systems: AMD, CommonJS and UMD. AMD are usually used client-side, CommonJS server-side (node.js) and UMD unify both systems.

The Kotlin ecosystem is still Java-based even when targeting Kotlin. This means that you are using Gradle, Maven, etc. instead of the node.js or JavaScript tools. That is because the compiler itself that transpiles to JavaScript is written for the JVM.

There is an inherent problem of compatibility between a dynamic typing language like JavaScript and one with static typing like Kotlin. The issue is that there are no type information in JavaScript, but Kotlin need them to work. So to use JavaScript libraries with Kotlin you have two options:

  1. You add type information
  2. You signal to Kotlin to ignore type checks

We are going to see how to ignore later. To add this information there is no smart way to do it. There is only the hard way: do it manually. Fortunately the Kotlin creators have included ts2kt a tool that translate TypeScript declarations in Kotlin ones. So you may be able to reuse them, but compatibility is not perfect. In fact for this tutorial we tried to use it for D3.js and it did not work without errors. That is a complex library, so your mileage may vary.

Our Project: Drawing With D3.js

The project for this tutorial is based on the D3.js example called US State Map. The D3 (Data-Driven Documents) is a famous library to create interesting and complex data visualizations. Our project repository is available on GitHub.

Given that the original code is released under the GPL3 so will be the code of our example. The idea is quite simple: a map of the USA with its states visible and colored according to the (randomly generated) temperature data. A tooltip will be displayed when the mouse hover a specific state.

This looping video shows a generated map.

 

We are also going to add a simple table listing the temperature data.

The project only deals with client-based code and not server-based.

Setup

There are many supported ways to use Kotlin for JavaScript: Gradle, Maven, IntelliJ IDEA and using directly the compiler on the command line. The suggested way is to use Gradle. For this tutorial we choose to directly use IntelliJ IDEA instead. That is because if you come from a Java you probably already know how to use Gradle. And in any case there is good documentation available to discover what plugin and dependencies include.

While it is by no means hard adding a build automation system this is not the focus of this tutorial, so we opt to use the simplest way.

Kotlin JavaScript Project

All you have to do is creating a New Project and selecting Kotlin (JavaScript). The name of our project is KotlinFunWeb.

We are also going to use also a library to simplify the creation of HTML code called Kotlinx.html, instead of using string concatenation or interpolation. So download kotlinx-html-js from the binary repository and add it to your project by going into Project Structure.

Adding a Kotlin library

We put it under the lib directory. We have it created just under the root project directory, but you can put it wherever you want.

The next step is creating a .kt file inside the src directory. We chose the name main.kt, but the name is not relevant. This file will contain our Kotlin code for this tutorial.

For the moment it will contain only the following code to test that everything works:

import kotlin.browser.*
import kotlin.dom.*

fun main(args: Array) {
    document.getElementById("tooltip")?.appendText("The first step")
}

The ?. is necessary because the element could not exist, so the result of getElementBy could be null. In such case the call to appendText will not be executed, but there will be no error. Apart from that, it looks like normal JavaScript code.

The last step is to add index.html, a normal HTML file that will include the JavaScript code.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<div id="tooltip"></div>
<script type="text/javascript" src="out/production/kotlinfunweb/lib/kotlin.js"></script>
<script type="text/javascript" src="out/production/kotlinfunweb/kotlinfunweb.js"></script>
</body>

The key part are the two script tags: the first one include the standard KotlinJS library and the second one include our code transpiled to JavaScript.

Once you build the project the resulting structure should look like this:

The directory layout of the project

The files under the out directory, including the directory itself, are generated when you build the project. The .meta files include code to support reflection and you do not need them to run the project.

All that remains to do is to access the file index.html in a web browser to check the result.

The Generated JavaScript Code

The generated file KotlinFunWeb.js should look similar to this:

if (typeof kotlin === 'undefined') {
  throw new Error("Error loading module 'KotlinFunWeb'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'KotlinFunWeb'.");
}
var KotlinFunWeb = function (_, Kotlin) {
  'use strict';
  var appendText = Kotlin.kotlin.dom.appendText_46n0ku$;
  function main(args) {
    var tmp$;
    (tmp$ = document.getElementById('tooltip')) != null ? appendText(tmp$, 'The first step') : null;
  }
  _.main_kand9s$ = main;
  main([]);
  Kotlin.defineModule('KotlinFunWeb', _);
  return _;
}(typeof KotlinFunWeb === 'undefined' ? {} : KotlinFunWeb, kotlin);

The code looks somewhat normal. You could notice that the name of the functions (e.g. _main_kand9s$) are mangled. This means that the original name is transformed and not copied verbatim. This happens because you can overload functions in Kotlin and this is needed to translate them in JavaScript.  This will happen also to the functions that you define, although you can control them with an annotation that we will see later. Also, your code is by default part of a JS module.

If you need to call Kotlin code from JavaScript it is also important to read the documentation for understanding how Kotlin types are translated in JavaScript. There are a couple of important things to notice:

  • There’s no 64 bit integer number in JavaScript, so kotlin.Long is not mapped to any JavaScript object, it depends on a class in the Kotlin runtime library.
  • kotlin.Any is mapped to JavaScript Object
  • kotlin.Array is mapped to JavaScript Array, but Kotlin collections (e.g. List, Map, etc.) depends on a class in the Kotlin runtime library.

In practical terms this means that  if you need to work with JavaScript it may be better to create the data objects with JavaScript and then use it from Kotlin than viceversa.

Copying The D3 Example

Now we are going to copy the aforementioned D3 example.

We have to download d3.v3.min.js (that I renamed in d3.js), uStates.js and include them under the lib directory.

Then we have to add this code to our index.html file.

<svg width="960" height="600" id="statesvg"></svg> <!-- svg to hold the map. -->
<script src="lib/uStates.js"></script> <!-- creates uStates. -->
<script src="lib/d3.js"></script>

This code adds the d3 library, the custom functions to display the USA States and the svg tag that will contain the map. You should also add the style tag and its content (not shown here) from the index.html included in the D3 example.

The file uStates contain the data on the shape of the USA states and a few functions to display a tooltip with temperature data when the mouse hover a state.

Using JavaScript In Kotlin

Replace the main function of our Kotlin code with the following.

fun main(args: Array) {
    js("""
    var sampleData ={};	/* Sample random data. */
	["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
	"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
	"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
	"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
	"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
		.forEach(function(d){
			var low=Math.round(100*Math.random()),
				mid=Math.round(100*Math.random()),
				high=Math.round(100*Math.random());
			sampleData[d]={low:d3.min([low,mid,high]), high:d3.max([low,mid,high]),
					avg:Math.round((low+mid+high)/3), color:d3.interpolate("#0295D5", "#F88909")(low/100)};
		});
    """)

    js("uStates.draw(\"#statesvg\", sampleData, _.tooltipHtmlJs);")

    val d3_kt: dynamic = js("d3.select(self.frameElement)")
    d3_kt.style("height", "600px")
}

Here we can see one way of combining existing JS code in a Kotlin application. We can just reuse some JavaScript code we have, as-is. Just notice that the function js should be used with string constants. Technically you can use compile-time constants. So interpolation with local variables is allowed in the form such as "my name is: ${name}", but only if name is a constant. So in practical terms only string constants works.

It is quite easy to understand what the code does: it generate random temperature data for each state and then it generate the tooltip for each state.

In the first js function we only changed the colors of the d3.interpolate call to match the colors of the Kotlin logo. The function d3.interpolate uses the given colors as the starting and ending points of the scale. Basically the first color is associated with the value 0, while the second one is associated to 1. Any value in between is associated to a color obtained by mixing the two extremes: the lower the value, the closer the color will be to the low extreme, the higher the value, the closer the color will be to the high extreme. Notice also how by using """ we are able to use a multiline string constant.

The first meaningful difference is in the second call to js. This is modified because we ported the original JavaScript function in a Kotlin one called tooltipHtml (we are going to see it later). Since the JavaScript code will be copied verbatim with the rest of our code we do not need to use the full qualified name of our function. It will be inside the JavaScript module generated by the compiler. Instead if you want to use Kotlin code from external JavaScript code you must use the full qualified name, including the name of the module of our project.

The third call to js is peculiar. Actually the call per se is normal, but its result is assigned to a dynamic constant d3_kt. The dynamic keyword switch off the static typing checks and so anything can be used as methods of d3_kt, even non-existing functions (e.g., d3_kt.heatDeathOfTheUniverse("now"). Of course, if you actually call a non-existing function at runtime the call will fail.

On the other hand if the function exist somewhere, for instance is defined in JavaScript libraries, the call will succeed. That is why the following call works as normal. It is important that you choose a valid name for the variable in the JavaScript environment. That is to say that if you pick one that conflict with an existing one in JavaScript, like d3, the code will compile, but it will fail at runtime.

The tooltipHtml Function

The tooltipHtml function receives as arguments the name of the state and the data on the temperatures. With them it generates the HTML that shows the data for the state.

The original function is concise, but also messy. It is a long concatenation of strings that is hard to read and easy to get wrong. The kotlinx.html library instead gives you a type-safe builder that guarantees the proper structure to the HTML code by forcing you to create  valid HTML.

First, we have to import the proper packages for kotlinx.html and traversing the DOM.

import kotlin.browser.*
import org.w3c.dom.*
import kotlinx.html.*
import kotlinx.html.dom.*
import kotlinx.html.js.*

Then we have to define the class that hold the temperature data and the color for a state.

data class Stats(val low: Int, val avg: Int, val high: Int, val color: String)

Finally we can see the code of the function.

@JsName("tooltipHtmlJs")
fun tooltipHtml (name: String, values: Stats) : HTMLDivElement
{
    return document.create.div {
        h4 { +name }
        table {
            tr {
                td { +"Low" }
                td { +values.low.toString() }
            }
            tr {
                td { +"Avg" }
                td { +values.avg.toString() }
            }
            tr {
                td { +"High" }
                td { +values.high.toString() }
            }
            tr {
                td { +"Variability" }
                td { +variability(values) }
            }
        }
    }

    return tooltip
}

The JsName annotation serves to control the name of the generated JavaScript function, which is needed if you want to call it from JavaScript.

As you can see the code is longer, but safer and cleaner. You simply cannot put a tr tag outside a table one, try as you might it will not compile. There are only a couple of things to remember:

  1. The first thing that you have to remember is to make sure that you pass a String where you need it and not an object.
  2. The second one is to prefix the call with the + operator. This is needed because Kotlin transform the + in a call to the unaryPlus function defined by the library. That function add the argument to the children nodes of the current node.

So this works by relying on smart conventions and good functional support. Which means that you can also create a similar library in Kotlin.

Remember that the table, td,  etc.  are nothing more than functions that accepts a lambda as one of their arguments. And according to the convention of the language you can put the lambda out of the parentheses if it is last argument and omit the parentheses if the lambda is the only argument.

The last thing to see is the variability column that we added. It display the results of the call of a variability function that we are going to see now.

The Power Of When

The variability function relies on the when expression to do most of the work and returning the appropriate String.

fun variability(state: Stats) : String
{
    return when(state.high - state.low)
    {
        in 1 .. 20 -> "Low"
        in 21 .. 50 -> "Medium"
        else -> "High"
    }
}

You can think of this expression as a smart swich statement. A traditional switch does not support complex branch conditions, but only constants value. Instead when does support arbitrary branch conditions and more.

Our example here shows how to use a range as a branch condition and return a corresponding String. The else branch is the equivalent of default and can be excluded only if the compiler thinks that all cases are covered by the defined branches. This happen, for instance, if the argument of when is a boolean expression and you include a true and a false branch.

It also important to remember that you cannot activate a cascade of branches omitting the break statement. That is because there is no break statement at all, the first matching branch is chosen and nothing else is checked. Though you can make sure that more conditions activate the same branch combining the conditions separated with a comma (e.g. in 1 .. 20, in 51 .. 60 )

When can be used as an expression or as a statement.

Adding The JavaScript Library

Before building the project now we have to include the JavaScript code for the kotlin.html library in the index.html file. Just makes sure to include it before your generated JavaScript code and after the standard runtime library.

<script type="text/javascript" src="out/production/kotlinfunweb/lib/kotlin.js"></script>
<script type="text/javascript" src="out/production/kotlinfunweb/lib/kotlinx-html-js.js"></script>
<script type="text/javascript" src="out/production/kotlinfunweb/kotlinfunweb.js"></script>

Once you build the project the result should look like this image.

A tooltip over a map showing the USA States

The Last Touches

The final code that you can see in repository also adds a table. We add a few styles, a call to a new function drawTable inside the main function and of course the mentioned new function and another one called drawTable. The code it is not complex, and you can see fully in the repository. Here we are only going to see a few interesting tidbits.

fun drawTable(tableDiv: HTMLDivElement, data: dynamic)
{
    val states = js("Object.keys(data);")
    states.sort()

    [..]

    for(i in 1 .. 50)
    {
        var tr = document.create.tr {
            td { +states[i].toString()}
            td { +data[states[i]].low.toString()}
            td { +data[states[i]].avg.toString()}
            td { +data[states[i]].high.toString()}
            td(classes = styleTable(data[states[i]])) { +variability(data[states[i]])}
        }

        table.appendChild(tr)
    }

   [..]

The data argument is a JavaScript object passed using js("sampleData") and the first thing we do is using a JavaScript reflection function to access the elements of the JavaScript object. While using the js function can be cumbersome for long pieces of code it is also nice and easy for such small things.

Inside the for cycle we can see how to add CSS classes to the HTML generated with kotlinx.html. We also call the styleTable function.

fun styleTable(state: Stats) = when
{
    (state.high - state.low < 33) && (state.avg < 33) -> "low"  // always cold
    (state.high - state.low > 33) && (state.avg > 33) && (state.avg < 66) -> "middle" 
    (state.high - state.low < 33) && (state.avg > 66) -> "high" // always hot

}

As you can see, you can also call the when expression without an argument. In that case the conditions are boolean expressions. That is to say the first branch that is true is executed. In similar situations when is not a replacement for a switch, but for a long chain of if-else. A clearer and more concise alternative.

When a function return the result of an expression you can use a short notation: omit parentheses and use a equal sign (=) instead. These are called single-expression functions in the documentation. You can also omit the return type when the compiler can determine which one it is.

Summary

Kotlin is a great choice for complex web applications if you already know it or if you are using the language for other parts of your application, such as the backend. It allows you to reuse either your competencies or the code, avoiding to duplicate the effort to write the same logic on both sides. It permits to write applications in a more efficient, productive and safe code compared to using pure JavaScript.

If this is not the case, and you are not using Kotlin anywhere else Kotlin could not be your best choice. In that case you might be better served with TypeScript. Kotlin for JavaScript is certainly not bad, actually we think that the Kotlin language is superior to TypeScript. But TypeScript is probably more widespread in that environment and it can be more easily integrated in a typical JavaScript or node.js workflow. Furthermore it can be easily used with the kind of lightweight IDEs that JavaScript developer are used to, like Visual Studio Code.

In our previous comparison between Kotlin and Scala, we said that one of the strong points of Kotlin is that it can be quickly learned by Java developers. Here the situation is reversed: TypeScript is more closely related to JavaScript, which means that it can be quickly learned by experienced JavaScript developers.

Why Kotlin Is The Best Language For Android Development

Why Kotlin Is The Best Language For Android Development

Kotlin is the first language officially supported by the Google for Android development other than Java itself. This alone is a significant accomplishment and a clue that Kotlin is a good language for Android. Another good sign is the reception of Android developers themselves to the announcement.

In this article we are going to explain the reasons why Kotlin is particularly good for Android development looking at two different aspects:

  1. we describe the features of Kotlin which are particularly relevant for Android development
  2. we look at the ecosystem around the language itself: things such as the IDE and the JVM on Android

Considering all of this, there is only one possible reason for not using Kotlin in new Android projects: you do not know the language. Do not worry, we can help you learning Kotlin.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


Language Features And Libraries

Applications for Android have some specific common features, typical of applications with a graphical UI. For instance, they make heavy use of asynchronous calls. Kotlin offers good support for them and even one or two libraries that can help when the language itself cannot.

Deep Interoperability

In a previous article we have talked about the great interoperability between Java and Kotlin which allows a smooth transition between the two or even a peaceful and productive co-existence. This interoperability involve all aspects: from the language itself to the bytecode produced. Something which is fundamental to allow reuse of important libraries that analyze it.

When it comes to the language itself you can find on the Kotlin documentation a complete list of the features for Java support. This interoperability is smart and deep. For instance Kotlin also support some conventions of Java development, as the following example based on getters and setters from the documentation.

import java.util.Calendar

fun calendarDemo() {
    val calendar = Calendar.getInstance()
    if (calendar.firstDayOfWeek == Calendar.SUNDAY) {  // call getFirstDayOfWeek()
        calendar.firstDayOfWeek = Calendar.MONDAY       // call setFirstDayOfWeek()
    }
}

This is great for Android development because the SDKs are obviously still made for Java. Thus by having such a great interoperability you can still write productive Kotlin code when you must use Java libraries.

Function Arguments

In Kotlin function arguments can be named and have default values. This simplifies reading and understanding at the call site and allows to limit the number of function overloads. Because you do not have to make a new function for every argument that is optional, you just put a default value on the definition.

Let’s compare definitions in Java and Kotlin.

 // Java
void drawText(int x, int y, int size, int spacing, String text)
{ [..] }

// Kotlin
fun drawText(x: Int = 0, y: Int = 0, size: Int = 20, spacing: Int = 0, String: text)
{ [..] }

And calling the same function in Java and Kotlin.

// Java
drawText(50, 200, 20, "hello");

// Kotlin
// using default values
drawText("kneel in front of the Kotlin master!")

// using named arguments
drawText(10, 25, size = 20, spacing = 5, "hello")

Nullable Types

In Kotlin you need to explicitly say that a variable can have a null value. By default it cannot. And this allows you app to avoid the common and dreaded NullPointerException at runtime, because most mistakes are caught by the compiler at compilation time. Null references are so risky that the creator of the first language with null reference call it the Billion Dollar Mistake.

var text: String = null // it does not compile
var unsafeText: String? = null // ok 

Kotlin takes advantage of the nullability or, at the opposite, the safeness of types at all levels. For instance, it is taken into consideration during checks.

unsafeText.length // it does not compile

if (unsafeText != null) {
  unsafeText.length // it works, but it is not the best way
}

After you have checked that a nullable type is currently not null you can use the variable in the same way as it is were not nullable, because inside the block it is safe to use. Of course this also looks cumbersome, but there is a better, suggested way, that is equivalent, but more concise.

unsafeText?.length // it works

The safe call operator (?.) guarantees that the variable will be accessed only if unsafeText it is not null.

Nullable types are particularly useful in Android because null is widely used. This can lead to a lot of bugs, but in Java you have not alternatives. Even looking at the official APIs you can see the @NotNull annotation all over the place.

In fact null it is used for several reasons, from performance to the lifecycle of the application that might require certain steps to be executed before you can properly initialize a variable. In such cases you might think that you cannot avoid using null, but you would be wrong. There are several ways to do it, including using late initialization or lazy initialization.

Lazy And Late Initialization

Late initialization works only for variable properties inside the body of a class. The variable cannot be of a null type. You add the modifier lateinit and then inside a method you initialize the variable. If you access the variable before initializing it you get a special exception that clearly indicate what you did wrong. The modifier lateinit was introduced to support dependency injection, but it can be useful in many other scenarios.

If you need a costant value instead you can use the lazy() function to delegate initialization to a function. Lazy accepts a lambda that is executed the first time the variable it is accessed. The function initialize the variable and return its value. The following times the variable is accessed the function is not executed, only the value is returned.

val computedValue: String by lazy {
    println("I am executed only the first time!")
    "A Value That Will Be Subsequently Remembered"
}

Lazy is useful when the computation of the value is costly and it does not change.

Data Classes

You need to use classes to group together semantically connected variables. In an Android app they are frequently used to represent the model of the application. The class just need to hold values, but typically you need a few standard methods to manage the data, getting and setting values of properties, etc. And you also have to update them every time you change the data.

Kotlin gives all that you need automatically, simply by using the data keyword in front of the class definition.

data class User(val name: String, var password: String, val age: Int)

That’s it. Now you get for free:

  • getters and setters (these only for variable references) to read and write all properties
  • component1() .. componentN() for all properties in the order of their declaration. These are used for destructuring declarations.
  • equals(), hashCode() and copy() to manage objects (ie. compare and copy them)
  • toString() to output an object in the human readable form Name_of_the_class(Name_of_the_variable=Value_of_the_variable, [..])"

For example, given the previous data class User

val john = User("john","secret!Shhh!", 20)
 
println(john.component1()) // it prints "john"
// mostly used automagically in destructuring declaration like this one
val (name, password, age) = john
println(age) // it prints 20

println(john) // it prints "User(name=john, password=secret!Shhh!, age=20)"

Is it mind blowing? No.

Is it a very useful thing? Yes, it is. It saves time and it allows easier changes to the model of an Android application, since you do not need to write custom functions to compare objects yourself.

Eliminating Utility Classes

Android applications need utility classes to add new features on existing classes or perform common operations specific to the app. Kotlin offers a couple of way to get rid of them: extensions methods and the possibility of using top-level functions without defining a class.

It is important to remember that both are syntactic sugar. Using extensions methods to extend a class you cannot access private or protected members of that class.

// extension method
fun String.bePolite() : String {
  return this + ", please"
}

val ask = "Pass me the salt"
println(ask.bePolite()) // It prints "Pass me the salt, please"

And if you want to use top-level functions in Java they still are inside a generated class. The generated class name usually is based on the name of the file in which the extension method is defined, but this can be altered with annotations.

// filename polite.kt
package strings

fun checkPolite(request: String) : Boolean {
    if (request.contains("please"))
    	return true
    else
    	return false
}

// a Java file
import strings.PoliteKt;

PoliteKt.checkPolite("prove P=NP, please");

There is another feature that makes utility methods more useful: operator overloading. You cannot define custom operators, but you can very easily use standard operators for your classes. All you have to do is defining functions with specific name and then Kotlin will translate the corresponding operator in this function on the call site. For instance if you define a function plus() for your class Kotlin will translate objectOfYourClass1 + objectOfYourClass2 in objectOfYourClass1.plus(objectOfYourClass2).

Functional Features

Functional programming is not a new programming paradigm, but its success it is relatively new. This is due to the increase of situations that require a lot of concurrency and parallelism. Android applications are not the best use case for fully functional applications, but they need to use asynchronous calls for UI interactions and often to call online backend services, so they would benefit from functional features. In short, Android applications benefit from functional features in the context of imperative programming.

The most common features are higher-order functions and lambdas. Higher-order functions are functions that accept functions as arguments or return one. Lambdas are anonymous functions that can be passed around. The problem is that only with version 8 that Java started including them, so many are forced to use a library, like Retrolambda. The reason because you cannot use Java 8 is explained in the later paragraph The Java Platform On Android. This is far from ideal, because the language itself does not support them and thus many libraries cannot take advantage of them.

A language like Kotlin, that include them from the beginning, allows you to take full advantage of them.

We assume that you already know the advantages of similar functional features, so what we are going to show is an example of how well and easily you can use them in Kotlin thanks to many of its conventions.

val strings: List = listOf("one", "two", "three", "Hello", "to", "Kotlin", "and", "Me")
// we first take only the strings longer than 3
// then we transform each string in its lowercase version
// finally we join them in one string
println(strings.filter { it.length > 3 }.map { it.toLowerCase() }.joinToString())
// it prints "three, hello, kotlin"

If you familiar with C# you will notice how similar this is to LINQ. This is also noted in the official documentation. And it goes to show how pragmatic Kotlin is. Kotlin took the best out of many languages and it added some more. In this case some more is the default name it that can be used when the lambda takes one argument. It is also the chance to put the lambda out of the parentheses if it is the last argument of the function and to omit the parentheses altogether if a lambda is the only argument (eg. for filter and map).

Concise, readable and easy to use. What could you ask more?

Kotlin Android Extensions

There are also Kotlin Android Extensions that allows you, among other things, to replace the annoying and bug-ridden findViewById() calls with synthetic properties. An example to clarify, from the documentation:

// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView.setText("Hello, world!") // Instead of findViewById(R.id.textView) as TextView
    }
}

There are some libraries for Java that allows you to do something similar, but they usually requires annotations. Kotlin offers a simpler way to do it, without any extra code or runtime.

Anko

Anko is a Kotlin library which makes Android application development faster and easier. It makes your code clean and easy to read, and lets you forget about rough edges of the Android SDK for Java.

Anko is a popular library that simplifies Android development with a lot of helpers. In fact, they are too many to mention all of them here. But we can say that the library is divided in several parts:

  • Anko Commons: full of helpers for intents, dialogs and toasts, logging, resouces and dimensions…
  • Anko Layouts: a fast and type-safe way to write dynamic Android layouts
  • Anko SQLite: a query component and parser collection for Android SQLite

We are going to show an example of Anko Layouts, because it also show another useful characteristic of Kotlin: type-safe builders. These are a safer and more concise alternative to configuration files and such things to describe data with a hierarchical structure. A typical example is a XML file used to describe a UI.

Using an XML file requires you to rewrite each time for each interface the same boilerplate structure. The only thing that varies is the data itself. This is not just boring, but also error-prone, hard to read and unsafe. Because it is easy to commit a mistake. Builders in Kotlin provide a better alternative.

You can transform the following Kotlin code (and let’s not even talk about the corresponding Java version…)

val act = this
val layout = LinearLayout(act)
layout.orientation = LinearLayout.VERTICAL
val name = EditText(act)
val button = Button(act)
button.text = "Say Hello"
button.setOnClickListener {
    Toast.makeText(act, "Hello, ${name.text}!", Toast.LENGTH_SHORT).show()
}
layout.addView(name)
layout.addView(button)

…in this much better version…

verticalLayout {
    val name = editText()
    button("Say Hello") {
        onClick { toast("Hello, ${name.text}!") }
    }
}

Which creates the following interface.

Example Layout defined with Anko

Example Layout from the Anko documentation

There is even an Android Studio/Intellij IDEA plugin to preview interfaces created with Anko.

Building Kotlin Applications For Android

There are some technical aspects to consider when building Kotlin applications for Android. They are relative both to Java and the tools used to develop for Android and involve many concerns of developers other than the language itself.

The Java Platform On Android

A table and a graph representing the percentages of devices for each different version of Android

Data on the different versions of Android coming from the official documentation

Experienced Android developers will already know that the history of Java on Android is complicated. For the rest, here there is a short summary. When Android launched there was not an open-source, stable and mature version of Java, since OpenJDK was just starting. So Android was based on a modified version of Apache Harmony. But with the maturing of OpenJDK the support of companies, like IBM, for Apache Harmony diminished.

Apache Harmony supported 97% of Java 6, but the project was ended in 2010, leaving Google to support the whole codebase, both its custom part and the open-source foundation. Furthermore Oracle sued Google also because it claimed Android fractured the Java platform. So Google switched the basis of Android from Apache Harmony to OpenJDK with Android 7, which also gave Android a new higher-quality foundation.

This means that, at the moment, most of Android devices support Java 6, while the last version of Android, and the future ones, should support the latest Java version. Although one problem is that there is still a delay between the OpenJDK and Android Java support because Google must adapt OpenJDK to its custom parts.

Given that the Kotlin compiler produce bytecode compatible for Java 6, Kotlin can safely brings its features to the majority of Android devices now. Thus it is the only practical choice for a modern and productive programming language for most Android developers.

IDE And Tool Support

The official IDE supported by Google for developing Android applications is Android Studio. This is the IDE that replaced the previous one based on Eclipse and it based on the open-source (community) version of IntelliJ IDEA. IntelliJ IDEA is developed by JetBrains itself and obviously supports Kotlin. But Android Studio will natively supports Kotlin starting from version 3, currently in pre-release status. There is a Kotlin plugin for previous Android Studio versions, too.

This is part of the official support of Kotlin for Android development. But it is not the only thing. We have already seen libraries and extensions made by JetBrains for Android.

Android Studio uses Gradle for build automation and Kotlin can be used as a language for Gradle scripting.

Finally, the Android SDK supports ProGuard, a tool to optimize, remove unused methods and obfuscate Java bytecode. Given the similarity between Kotlin and Java bytecode ProGuard also works well for Kotlin. This is a good example of how deep goes the effort of JetBrains to maintain compatibility between Java and Kotlin and why they do that.

APK Limitations

Apart from Java support there are many small differences between the official JVM and the one supported by Android. One that matters particularly for Android development is the limit on the numbers of methods and fields in your application: 216, which means a bit more than 65000. The Kotlin runtime and standard library combined adds around 7000 methods, which is circa 10% of your method count. This is not an insignificant amount, but using ProGuard it can be reduced substantially, even to 42!

Furthermore it can actually be an advantage if it allows you to get rid of an alternative library. Good candidates are libraries that introduce small functional features or improve the productivity of developers, or the quality of life. The developers of App Lock managed to reduce the total method count by 10% and the total lines of code by 30% with a conversion from Java. Another app developer reached a reduction of 20% lines of code.

Also, to put things in perspective, 7000 methods are not that much compared to the ones of a library like Google Guava, that has almost 15000 methods. And let’s not even talk about the numbers of languages like the 50000 of Scala or the 30000 of Groovy. Such high numbers make them practically unusable for Android development, no matter the advantages.

There is also a limit on the size of the APK that you can upload on the Google Play Store. This limit is 100MB. Even without that artificial limit there would also to consider the limited space on the users devices and possibly the costs of transferring the APK over metered connections. So the fact that Kotlin adds only around 1MB to the debug APK, and even less to the release one, it is a good thing.

Bottom line: using Kotlin have consequences in light of APK limitations, but considering the alternatives it is a no-brainer.

Java Conversion Tool

JetBrains has done a solid job with their Kotlin plugin and its ability to auto convert Java to Kotlin. It can get your class 60–70% of the way there, leaving you with some tuning and idiomatic/stylistic things to take care of.

How we made Basecamp 3’s Android app 100% Kotlin

JetBrains developed a tool to convert Java code in Kotlin. This is a tool that can be accessed in many ways, in the online test environment, which make it useful for learning, and in the IDEs, like IntelliJ IDEA and Android Studio, which make it useful for learning and coding.

It is a very useful tool, but as most automatic conversion tools it is not perfect. Studying the results is needed for learners to understand the basics use. While it may not break your class, it does not always produce the best code, so it is also useful to study the results to modify them in the idiomatic and suggested way of using Kotlin.

Compilation Speed

The time necessary to compile Android application has been a pain point even with Java for some time, since the adoption of Gradle. With Kotlin the speed is now great, even for people that during the beta criticize it for its slowness. It is even better than Java with Retrolambda.

What does it mean great? On clean builds a Kotlin application it is slower than a Java one by around 15%. This remain true both for the first build and for subsequent builds with the Gradle daemon. But where it counts, that is to say during development when you change a few files at once before recompiling (incremental builds) it is actually faster than Java itself.

Drawbacks

The language Kotlin is already mature, but there is still work to do in the ecosytem around the language.

Annotation Support

Some advanced features like Java annotation support and reflection were not greatly supported in Kotlin up until the last few pre-release versions. A frequently requested feature used to be support for annotation processing in Kotlin. In particular many people wanted support for ButterKnife, the famous Android library that uses annotation to bind field and methods with views. There were already alternative to do the same things of ButterKnife with Kotlin, but good annotation support was needed.

Now stability and support is there, but there are still difficulties in some cases, if nothing else from configuration and changing apt with kapt. Kapt is the annotation processing tool for Kotlin that brings support for dagger, a fast dependency injector for Android, and dbflow, an ORM android database library that writes database code for you. At the moment using kapt noticeably slow compilation speed. The Kotlin ecosystem is mostly there, but there are still annoying problems to fix.

Analysis Of The Code

One way that Kotlin managed to be so well compatible with Java, and with so little overhead, is that a lot of the smart stuff of Kotlin is in the compiler and not the generated bytecode. Which means that reflection is costly and requires a specific library in addition to the runtime. You need to add kotlin-reflect which adds almost 20.000 methods to you app which is clearly very far from ideal. The workaround is to use reflection in Java or use the Java reflection support in Kotlin. For instance you can use String::class.java.methods to access the Java/JVM methods created by the Kotlin compiler.

The first option requires you to keep using Java, at least in some places, but it is guaranteed to work. The second one allows you to use exclusively Kotlin, but the results may be different from what you expect. That is because the productivity granted by Kotlin relies on operations behind the scenes. For example to allow you to use default values in Kotlin the compiler generates a Java method for every combination of arguments.

Another current problem is the lack of static analysis tools for Kotlin. It is true that the Kotlin compiler is smarter and safer than the Java one. And you can actually integrate the command line compiler in your workflow. Still this is undeniably a current weakness of Kotlin, which probably will remain for some time given that the official Kotlin parser is open-source, but tightly integrated in the compiler. Thus it is not easy to extract and reuse it.

Is Kotlin The Swift Of Android?

Kotlin and Swift logos

Kotlin and Swift started being developed roughly at the same time, but Swift was released first. So there is a certain reputation of Kotlin as The Swift Of Android. This is not so much because one inspired the other, but because both of them were developed to bring a more modern programming language to their respective operating systems. They intend to be an upgrade to their predecessors.

In that sense the languages have similar needs of keeping compatibility. At the very least, they need to keep it at the design level because they target the same environments and they surely target the same developers. They largely succeeded. And being languages developed at the same time they have also similar concerns and features, for instance they are both languages in which type inference, nullability and constant values are concerns.

So you could say that Kotlin, at least for Android, is like Swift for iOS. This is a good thing because it simplifies development and understanding. You might not have the same developer working on both the Android and iOS version of one app, but having similar languages makes easy for both teams to coordinate between them and follow the same structure. This increase productivity and reduces the risks of different bugs introduced in different versions of the same app.

Kotlin Is Better Than Swift

One important difference, though, is that, as usually happens, tools and language design of Apple is a bit of lower quality than the alternatives. This happens because Apple has really no competition in the development part. If your customers choose Apple you, the developer, have really no choice, you must work with what Apple gives you.

In fact a common criticism is the instability of Xcode, compared to Android Studio. Also Swift development may have been too quick: there have been already three versions of Swift in three years and each version introduced breaking changes. While it is better to have an updated language than a stale one, a language that moves too quickly it is also not ideal for developer productivity.

So we would say that Kotlin for Android is better than Swift for iOS: it has better tool support and it is a more stable language.

Summary

Kotlin is a language designed to be easy to use and extremely productive. It brings to the Java world many of the modern features that it lacks and it adds some new ones that fits the style and needs of experienced Java developers. It does the same for Android development and on top of that adds libraries and tools to simplify common development patterns for the mobile OS.

It is not an accident that Kotlin is loved by Android developers and officially supported by Google. It works great and it is the best programming language for Android development that you can use right now.

JetBrains started focusing on supporting Android developers and got great popularity among them. Now it can use that traction to challenge Java in other areas. However every Android developer can now benefit from those investments and enjoy the results.

What are you waiting for? What is your reason for not using Kotlin for Android development?

Kotlin vs Scala: Which Problems Do They Solve?

Kotlin vs Scala: Which Problems Do They Solve?

Scala and Kotlin are the two contenders for the Java throne. At the very least they are the two main languages to consider using in a JVM based application.

They aim to solve the same problem: providing a better Java but they do it in a very different way:

  1. Scala has been designed in the Academia, Kotlin in a leading software company. The background in which they are born explain most of their differences. Scala has been born to try some cool ideas on functional programming and mixing different paradigm. Kotlin is about solving practical problems. Kotlin designers cared about compilation times and great tool support, because those things matter to programmers, even if they do not sound exciting for other language designers.
  2. A great merit of Scala is that it proved to be possible to build another major static language for the JVM. It made clear that the JVM was flexible enough to allow language designers to benefit from it. Kotlin arrived much later. At that time people were not excited by the idea of having a new JVM language, they started caring about the practical aspects.

In this article we are going to compare Kotlin and Scala mostly for their uses, not their technical features. We are just going to make a general overview of the features of these two languages, and we are mostly concentrating on what they are designed for.

100+ Resources to Learn Kotlin

Receive over 100 resources to learn Kotlin in the right way.

You will receive the guide in your inbox, ready to be read on any device you want, when you have the time.


Is There Anything Wrong With Java?

Both Kotlin and Scala runs on the JVM and compare themselves to Java. This begs the question: is there anything wrong with Java?

Well, certainly Java did a lot of things right. It was an evolutionary language, rather than a revolutionary one. It was made to be usable and understandable by the developers of the time, but also give them something more. Its promise: Write once, run anywhere is alluring now as it was at the time.

In fact Java is probably the most used programming language in the world. Java is also arguably the most used language in the enterprise world and the most widely taught language in computer science courses.

So Java is great, just like C is great. But just like C, Java is old.

And although Java has evolved more than C, and luckily in a more organized way that C++, it is lagging behind many other languages. It is still certainly good enough for daily use. And many developers are happy with Java. But many compare it unfavorably with C#, which is a language with similar purposes. Or really almost any other modern language.

It is not a secret that many developers, and companies, want something more productive and I dare say fun to use. There is a lot of technical criticism of Java itself and a lot of baggage in the language which limits what it can be made easy to use. This is the curse of success: so many people use it that the designers cannot really change the fundamentals even if they had discovered they were wrong about something.

Why Scala And Kotlin

Scuola di Atene a painting of Raphael

For many years developers have built new languages on the JVM. Many of these languages attempted to be a mix of improvements over Java and offering something more than Java. That is to say many tried to improve the developers productivity and experience, while doing the same things that you can do with Java and/or also tried to make something different, like a dynamic language or one similar to Lisp.

Scala stands for Scalable Language, a language designed to scale with the needs of its users, while Kotlin is the name of an island, just like Java.

We picked Kotlin and Scala because they are both quite popular, statically typed languages and good representatives of two approaches: Kotlin is purposefully made as an improvement over Java while Scala is a different language altogether. Kotlin gives you everything you need, Scala gives you everything you may want.

Scala has the right features, but its most obvious deficiency is very slow compilation

You can already find articles of people that decided to move from Scala to Kotlin. In some ways the creators of Kotlin did that too. In fact, the  quote comes from an interview with the lead Kotlin developer that explained one of the reasons because they decided to create Kotlin. The other one, of course, was to create a better language than Java, but that was still compatible with the JVM.

This does not necessarily mean than Kotlin is better than Scala, of course. On the contrary it means that Kotlin designers think that Scala is a good language. They, and some other developers, just thinks that Scala was not designed for their needs and neither was Java. So they made Kotlin.

A Comparison Of A Few Features

As we said in the introduction we are not listing all the technical features, nor we are looking at the syntax. We think that too much details can be confusing especially without a context. Furthermore nobody choose a language with a checklist. Nevertheless it is important to  see some significant features and the approach the languages pick.

Object-oriented

Java is a language designed for object-oriented programming, but not everything is an object. The basic types, like numbers, are represented as primitive types. In Scala and Kotlin everything is an object and can be accessed as such. This is not necessarily a deliberate choice, since there is a slight penalty for using reference types instead of primitive, but it is due to the fact that in JVM you cannot define value types. So to get the advantages of a smarter type systems you can only implement it with reference types.

Scala and Kotlin supports also other programming paradigms. Although Kotlin remain mainly an object-oriented language it include basic aspects from all programming paradigms that are advantageous in daily programming.

Functional Programming

Kotlin supports fundamental functional features, such as lambdas and higher order functions. But it does not fully support functional programming paradigm. As always, it goes for the pragmatic bits that can be useful to the average programmer, without requiring a PhD in Computer Science to be used proficiently. For example:

  • independent (top-level) functions are fine and you do not need to make utility classes to contain disparate functions
  • Kotlin defines expressions rather than statements, so you can assign to variables things like the result of if
  • you can easily define immutable data with val, instead of var. No need for modifiers like final

Scala supports equally well the functional and object-oriented programming paradigms. It was designed with this goal in mind, and it has most features that you will find in Haskell, but not in Kotlin or Java, such as currying, memoization, partial application, type classes… It has the whole package, so to speak.

Small Things

Every language can be different. Both Kotlin and Scala have many productivity features that are standard in new languages, but they were not so when Java was created, things like type inference and quick ways to create a singleton or a data class.

Kotlin

Given the focus of the language, Kotlin has all the essentials and little else, although it also has first-rate support for null-safety and interesting things like smart casts. Smart casts means that if you check the type of a variable that is automatically casted to the new type, of course if it actually is a variable of that type. Generally speaking Kotlin uses very well its set of features, rather then adding more things. For example you can overload operators, but only the basic operators that are already in the language, you cannot define new ones.

Kotlin also ease the creation of an internal DSLs, or fluent interface. It does that with lambdas and the help of some syntactic sugar. Like the fact that the last argument of a function, if it is a lambda, can also be put outside of the parentheses. This is useful to reduce the need for complex string interpolations. For instance, this example uses a library to create HTML.

createHTML().table {
    for (language in languages) {
       tr {
           td { +language.name }
           td { +language.popularity }
       }
    }
}

Scala

Scala instead has all you may want from a language that need to be both functional and object-oriented. Although it has some small flaws of its own, for instance, the managament of null-safety is less efficient and natural than in Kotlin.

Scala also excels in the creation of complex internal DSLs, by including  macros and the chance of creating custom operators. Using Scala you have great freedom and many chances of hang yourself. For example, many developers lament the overuse of arcane custom operators whose purpose is not really clear from the code itself.

It only a slight hyperbole to say that if you imagine any construct you can do it in Scala. So you have to pay attention to the imagination of your developers, and their competence.

Interoperability With Java

People working together

Kotlin Was Designed To Work With Java

Kotlin is a language created to maintain compatibility with Java. It even has functionalities to facilitate interoperability with Java, like making easier to call Kotlin idiomatic code from Java. So you can keep developing legacy software with Java, but creating new ones with Kotlin.

One reason because Kotlin is so popular on Android it is due to its compatiblity with Java 6, which is largely the current Java version of Android. So Kotlin brings some features that are already in Java 8, but are not available to Android developers.

Interoperability with Java is not an accident, or simply what you can get by using a language that runs on the JVM. JetBrains designed Kotlin aware of the current Java ecosystem and situation. They tried to bring the most value in the way that was easier to use. This compatibility get down to the structure of the bytecode itself. And was one of the reasons that lead Corda to pick Kotlin over Scala.

Scala Can Work With Java

Scala was created to run on the JVM platform, for easier deployment, but compatibility was not really a primary objective. This starts with the technical side and keep going with the language features. For instance the recent versions of Scala requires Java 8.

This, coupled with the features of the language, means that if you want to develop with Scala going back-and-forth to Java is hard and not really an intended use case. Working with an existing Java codebase? Yes, you can. Keeping developing Java software with Scala? Not really a good idea.

Compatibility is also made difficult by the fact that Scala support functional programming as well as objected-oriented programming. If you use its advanced functional features you cannot really do much with that in Java. And, even if you could, your Java programmers might not know how to use them.

Different Philosophies

Many successful languages have precise objectives and a specific philosophy of what programming should be. Kotlin and Scala are no different. Kotlin wants to be a better Java, while Scala plans to be much more than Java.

Kotlin Is A Better Java

You could argue that Kotlin has fulfilled its original objective: it became the first language to be officially supported for Android development, other than Java. This is undeniably a great achievement that prove a couple of things: the Java community loves Kotlin and it is easy to introduce Kotlin to Java developers.

Kotlin is a pragmatic language designed to improve productivity and being easy to learn for Java developers. It is mainly designed to be Java like, but with a bit of C# and even Scala, on top of the Java model. It adds features that Java programmers want, like lambda and basic functional features, and simplify life, like smart casting and non-nullable types. Kotlin additions in many cases are what is usually called syntactic sugar. A more concise way to express common patterns used by developers.

While Kotlin offers some support for functional programming it really does it to accomplish easier procedural or imperative programming. For instance, individual functions can now be first class citizens of the language. Kotlin prefers to be simple rather than being formal.

Scala Is More Powerful Than Java

Scala never tried to do any of that that. It was designed to be more powerful than Java. Or more generally, a better language than Java. Scala was designed to do things that Java could not.

Scala offers great support for advanced functional programming, in fact functional programming is a first-class citizen just like object oriented programming. This adds complexity and make Scala a famously hard language to learn and use. This is not strictly a flaw of the language, you can do more, so there is more to learn. You can mix paradigms and thus you must know them all.

This can be an advantage in the rights hands and a disadvantage in the wrong ones. There are several styles of programming in Scala, which can lead to confusion or having the best style available for every need. In any case this lead to higher costs of development and higher wages for good Scala developers. Which can be a good or a bad thing depending on who you are.

The World Around The Languages

A representation of Earth half in daylight and half in the dark

Community

Scala has a larger community, if nothing else because it has been around longer. Unless we are talking about Android development where Kotlin probably has already the upper hand. Just look at the 2017 Google I/O to see the enthusiasm with which Kotlin was received.

The relative lack of native libraries is somewhat mitigated by the excellent Java compatibility. But robust libraries with idiomatic Kotlin code are not always available in Kotlin or they are not as deeply developed as the ones for Scala and Java.

Documentation And Easy Of Learning

Both languages have a good documentation, but surprisingly the Scala longevity might be a problem here, because some parts “are in state of flux” (for example the Scala Wiki) or might be outdated now that the official Scala website has been updated. Furthermore you must train developers in Scala and train them in your style of development. You cannot just pick some Java developers and give them a few days of training. Actually, if you pick a typical Java developer you might even have to train him in functional programming.

You can do that with Kotlin. Corda actually did just that:

Excellent documentation and tiny standard library makes it a very fast language to learn. We do not explicitly advertise our positions as needing Kotlin experience and have been hiring people who didn’t know it already, with ramp-up times in the range of 1-3 days before the new team member is producing idiomatic code.

Kotlin is easier to learn and easier to try, it has a great online test environment with examples and which can even convert Java code. So you can instantly see how to do the same stuff you do in Java.

Tooling

Both Scala and Kotlin are statically typed languages which allows a whole class of compiler checks and static analysis tools. So the potential is similar. Having said that, tooling is better for Kotlin, which is unsurprising given that is created by JetBrains, the famous software house of programming tools. As for the documentation, it is not really a case of Scala is bad, but Kotlin is awesome.

Previously the official Scala website offer an Eclipse-based IDE. We reported this fact and that is why you are going to see mentions about it in the comment. Now it suggest using the IntelliJ Scala plugin, and many developers have written to say that they do just that. So there is a good IDE for Scala.

However Kotlin is already integrated in IntelliJ IDEA and Android Studio. It also has a plugin for Eclipse. Furthermore IntelliJ IDEA has also the same conversion tool and examples available online, so you can easily convert Java classes and learn the language with interactive examples. You can also use a standalone compiler if you need a more advanced integration with your workflow.

Summary

Kotlin design seems to take an holistic approach: its authors considered how each design decision affected the whole development experience. Was a feature really necessary or were there alternatives? Would that choice make the compiler slower? Would it make more difficult to provide good tool support?

Scala designers seem not to bothered by pragmatism, as they follow another great idea. Scala reminds me of C++: there is always place for one more feature. Sure, they say that you can adopt your own subset and reduce the complexity of the language as it is used in your organization. It could work in some places, but I am not sold to the idea for everybody.

Many people moved to Scala with hope for a better language and unsatisfaction with Java. Most of the people that had the first motivation are happy with Scala. Many of the ones that were simply unsatisfied with Java are a bit perplexed by the complexity of Scala. It is not the right language for them. It is simply something different from plain old Java.

Kotlin is probably a better language for them. Every Java developer can easily pick Kotlin, not so for Scala.

If you need a Java-like language that is more productive than Java itself, you should go with Kotlin. If you need Haskell plus Java, you should go with Scala.

We hope that this pragmatic comparison has been useful. But if you want to get a more technical comparison and a look at the syntaxes of the two languages we suggest you look at Scala vs Kotlin, or a series of three articles by A Java geek.