What is Kotlin Coroutines?

Video overview of experimental part of interesting programming language
07 August 2017   469
Kotlin

Statically-typed programming language that runs on the Java Virtual Machine and also can be compiled to JavaScript source code

Some APIs initiate long-running operations (such as network IO, file IO, CPU- or GPU-intensive work, etc) and require the caller to block until they complete. Coroutines provide a way to avoid blocking a thread and replace it with a cheaper and more controllable operation: suspension of a coroutine.

Coroutines simplify asynchronous programming by putting the complications into libraries. The logic of the program can be expressed sequentially in a coroutine, and the underlying library will figure out the asynchrony for us. The library can wrap relevant parts of the user code into callbacks, subscribe to relevant events, schedule execution on different threads (or even different machines!), and the code remains as simple as if it was sequentially executed.

Many asynchronous mechanisms available in other languages can be implemented as libraries using Kotlin coroutines. This includes async/await from C# and ECMAScript, channels and select from Go, and generators/yield from C# and Python. 

In this report, Roman Elizarov talks about Kotlin Corouties.  Coroutines that are presented in Kotlin 1.1 in a massively redesigned form versus the original plan. This talk assumes familiarity with previous year's presentation (only a short overview is given) and focuses on challenges that were encountered during the implementation of the original vision on Kotlin coroutines.

Roman is tutor developer at JetBrains and ITMO university.

How to convert list to map in Kotlin

Two ways to convert list to map in Kotlin, with code examples
31 October 2017   507

For example, you have a list of strings like:

val list = listOf("a", "b", "c", "d")

and you need to convert it to a map, where the strings are the keys.

There are two ways to do this:

The first and most performant is to use associateBy function that takes two lambdas for generating the key and value, and inlines the creation of the map:

val map = friends.associateBy({it.facebookId}, {it.points})

The second, less performant, is to use the standard map function to create a list of Pair which can be used by toMap to generate the final map:

val map = friends.map { it.facebookId to it.points }.toMap()