KotlinConf is thé conference to visit if you’re into Kotlin development. JetBrains introduced KotlinConf in 2017 in San Francisco with over 1.200 participants and 50 speakers. In 2018 it took place in Amsterdam with over 1.300 participants and 60 speakers. This year the conference was hosted in Denmark’s Copenhagen at the Bella Center, Scandinavia’s largest conference center. Five colleagues of Ordina Belgium’s JWorks unit were very enthusiastic to attend the conference for the first time.

KotlinConf photo collage #1

Table of contents

Day one

Opening keynote by Hadi Hariri and Andrey Breslav

Introduction

Hadi Hariri Hadi kicked off the keynote by saying that this year is the third time that KotlinConf has sold out once again with over 1.700 participants.

A free live stream of all the different rooms would be made available for anyone to attend. Some additional numbers were given: the conference counted over 60 speakers, 35 volunteers and there were people visiting the conference from over 86 countries. The final session of the day would be about a new product announcement of JetBrains, followed by an evening party.

Andrey Breslav

Hadi then introduced Andrey Breslav, CTO and Lead Language Designer of Kotlin.

Intro Andrey Breslav

Evolution of Kotlin

Andrey continued with some numbers on the usage of Kotlin for each of the major versions:

Kotlin version Usage
1.0 200.000 people
1.1 500.000 people
1.2 2.100.000 people
1.3 (current version) 4.000.000 people

We can clearly see that Kotlin keeps growing at a really nice rate which looks very promising for the language. For JetBrains, important numbers like these, validate the quality of their product. For them it was clear from the beginning that Kotlin had to have an open ecosystem. One welcome to every body and open to anyone who wants to build on top of Kotlin. It was always meant to be more than just a piece of software, it was meant for people united by ideas.

Andrey went a bit deeper on the Kotlin ecosystem and explained that they wanted Kotlin to become a default language regardless of the level of experience, platform, scale or type of application. For them to achieve that, it was all about lowering barriers.

Kotlin Ecosystem

Different platforms

Server-side

Kotlin has been friends with Spring for a long time by now. The first official support arrived since 2017 with Spring Boot, Web MVC, and Web Flux coroutines support. Ktor, used for building asynchronous servers and clients in connected systems and also developed by JetBrains, is gaining more traction and is also used more and more at JetBrains. Some other companies that have been using it are Expedia, Intuit and the Norway Tax Office.

Android

Android has been Kotlin-first since this year. 53% of professional Android developers work in Kotlin and 60% of the top 1.000 apps have been written in Kotlin.

JetBrains wants to further invest in mobile multi-platform for both Android and iOS by allowing business logic reuse between the different platforms. Planboard, PlanGrid, Careem Driver’s app, Cash App, Yandex Disk & Yandex Maps, Quizlet, and VMWare Workspace One are some of the apps where business logic is already been reused between the different platforms.

What’s coming in 1.4

Kotlin 1.4 is said to be released in Spring 2020 and a lot of focus is being put on quality and performance. Currently, 93% of users get code completion results under 500ms but in 1.4, code completion is said to become about three times as fast. IDE Gradle imports should also happen twice as fast and it should use 75% less memory. A lot of improvements are also said to be done for Kotlin/Native compilation time.

A new compiler

One of the biggest pains in Kotlin projects is the build speed, especially as the project get bigger. This is why JetBrains has been working on a completely new compiler! It is going to be fast, uniform and pluggable. Some parts are coming in Kotlin 1.4 whereas others are coming in later versions. They are aiming on 5x faster compilations. This however won’t be for version 1.4.

New Kotlin compiler performance

The new compiler also comes with a new type inference and will ship in 1.4. This will fix numerous bugs that they couldn’t fix in the previous implementation as it was not flexible enough and it will enable new language features. It can be evolved and extended to enable even more language features later on.

Kotlin has three different backends: Kotlin/JVM, Kotlin/JS and Kotlin/Native. In 1.4 they want to offer one single unified backend for all three of them. Kotlin/Native is built from the beginning in this new unified infrastructure so Kotlin/JVM and Kotlin/JS both need to be migrated. This way, if a bug gets fixed this will mean that it will be fixed for all platforms right away!

An experimental feature in 1.4 is KLIM, a new portable format. This includes a new unified format used within the different platforms.

Multi-platform

Kotlin multi-platform

JetBrains want people to be able to share code and skills across the whole platform. The idea is that you write common Kotlin logic that can be used in any platform that works everywhere. If you want to interact with a platform, you can interaction with platform specific versions of Kotlin.

Seeing as libraries are somewhat the bulk of the Kotlin ecosystem, it is clear to JetBrains that they need to pay enough attention to help people writing libraries. They plan on doing this by adding a few tools to help people make libraries and to make their APIs robust and stable over time. This will be achieved with a new library called Author’s Mode that will demand explicit visibility and explicit public types where required.

JetBrains is also working on Dokka, a documentation generation tool that will support multi-platform libraries.

Mobile multi-platform.

Coming in 2020 will be the possibility to run and debug iOS Kotlin apps in Android Studio through a closed-source plugin. Note that this is not going to replace Xcode as you will still need it for certain things, but for the normal development cycle you will be able to stay within one IDE.

Kotlin/Native already works on TvOS and WatchOS, and to demonstrate this, an app called Kotlin Locator was made to play a treasure hunting game during the conference. The app comes with a WatchOS companion app so that you could try it out yourself.

Browser multi-platform

A new feature has been added to allow quick reloading in Kotlin/JS, similar to other frontend frameworks. A lot of improvements were also done on the JS binary size, compressing it further down by quite a bit, reducing the final size of an app. Work is also done on JavaScript operability with support for ES modules and Dukat which will connect Kotlin types with TypeScript types.

WebAssembly + Kotlin

WebAssembly is a new web standard supported by all major browsers. Basically it is a special virtual machine to run all kinds of different code and Kotlin wants to be run in there too. Currently they have a prototype that they are working on.

Data science in Kotlin

Not all users of Kotlin are programmers. Data scientists have also been using Kotlin in combination with Jupyter, Spark and lets-plot.

Language changes

KT-7770 was mentioned. A ticket about function interfaces created by Sergei Lebedev three years ago.

Function interfaces

A function interface has a single method and you can use it as a function type. This also improves the Java inoperability if you want to migrate Java code from Kotlin code without things breaking.

Language evolutions

It is important for JetBrains to keep the language modern although they are aware that it is not very desired to have breaking changes in between updates. If something becomes less useful it will be faded out and removed later to avoid legacy from building up. In general, updating from one version to another should remain easy and desired. JetBrains will provide feedback loops to keep developers informed of upcoming changes and to stay in touch with the community. If migrations are necessary, they will provide the necessary guides or tools to help developers migrate their code.

For all details, rewatch the keynote on YouTube:


Putting down the golden hammer by Huyen Tue Dao

Andrey Breslav

I suppose it is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail. - Abraham H. Maslow

Huyen started her talk with the quote above. Given a new tool or framework, it is common for people to get a bit too enthusiastic with it and to exaggerate in the usage of it, treating it as a golden hammer.

Huyen explained to us that she questioned herself on how to write better Kotlin code. And in particular by avoiding her own hammers and biases. As background information, she told us that she worked with Java and C++ before she got into touch with Kotlin.

The main anchor that caused her to question herself was the keynote from KotlinConf 2018 where the following was mentioned by Andrey Breslav:

Our main focus, our main motto was to make a pragmatic language. Getting things done, and turning your thoughts into working software without jumping through hoops.

Experienced developers praise the following regarding code:

  • Readability over concision
  • Reuse over Expressiveness
  • Interoperability over originality
  • Safety/tooling over soundness

Based on that, the following questions came up to her:

  • “When might we be using Kotlin features as golden hammers?”
  • “How can we use these features more pragmatically and hopefully write better Kotlin”

Some hammer-proofing points to ponder:

  • Readability
  • Reusability
  • Maintainability
  • Intentionality

Type inference

Type inference

Kotlin has a smart compiler that can infer things like the type of a variable. The hinting feature in IntelliJ helps a lot with showing the exact type of a value or object as sometimes it might be possible that you expected a certain type but it’s actually a different one.

For example, when declaring a list of numbers but also adding a string to it, causes it to change the list’s type to a list of Any. If we would want to have a compiler error for this we would need to define the type explicitly like val crewlist: List<String>.

Something to keep in mind in this case is that we should not depend too much on the hinting feature as you can only see these in IntelliJ and not for example when reviewing a pull request. It is important to have the code speak for itself. In that way it is important to explicitly specify the type in certain cases.

Implicit parameter

Implicit parameter

Depending on the context, it is not always easy to tell what the it stands for. Especially in a complex context, you should rather specify the variables to be more explicit.

Scope functions

Scope functions

It is easy to exaggerate in the usage of scope functions such as apply, also, let, run, with. We should be weary of combining too much of these as it causes us to lose track of what this exactly represents and it creates unnecessary complexity making maintenance more difficult.

Do not feel obligated to stretch yourself or your code because it does not feel Kotlin-y enough as Kotlin is meant to be a pragmatic language. The code above can be rewritten as follows:

Scope functions improved

Extension functions

We can define extension functions to extend existing APIs that you may otherwise not control without subclassing. A good practice is to make use of this to keep classes and APIs minimal, only containing intrinsic properties and behaviours and to keep your class abstractions pure.

Huyen mentioned the Kotlin for Java Developers Coursera course in which the question was asked on why extension functions are so popular. We can exaggerate with extension functions. For example if you make every single function an extension function of an existing class. We should think about what makes a good utility to a class and we should not make extension functions of too specific functions but keep them as regular functions.

Nullability and nullable types

Nullability

? and !! can be valid ways of handling nulls with thought to intentionality and maintainability. Kotlin has nullable types whereas Java does not. If you pull in Java methods into the Kotlin world, you can stumble upon cases where it is not clear if something is nullable or not, resulting into unchecked nullability issues.

Null safety checks with ? can be bad too and can obfuscate both good assumptions and bad assumptions. Failing silently is often a bad and undesired thing. Because of that, it can be a good approach to prefer to use !!. !! is not inherently evil but requires careful use based on good assumption or because you just KNOW that a value is non-null.

Nullability tips


Kotless - Kotlin serverless framework by Vladislav Tankov

Serverless is a cloud computing execution model, in which the cloud provider runs the server and dynamically manages the allocation of machine resources - wikipedia

Vladislav Tankov

Vladislav mentions that there are three simple steps in building a serverless application:

  • Take small elements: stateless functions
  • Compose them with events into an application
  • Deploy them to the cloud runtime

This deploy step is often done with Infrastructure as Code (IaC). However, deploying serverless applications with IaC is often not so simple. It can require more than 100 lines of config, for a simple hello world application that contains 5 lines of code. For a simple website it can even go to more than 1.000 lines of config.

On top of that, IaC often uses a separate language to express the configuration. This requires developers to learn yet another language.

As a solution to these concerns, the Kotless framework is introduced.

Kotless

Kotless is an IaC tool for Kotlin serverless applications. It consists of two parts:

  • A DSL that provides annotations to define routing, scheduled events, etc.
  • A Gradle plugin to configure how the serverless application should be deployed.

The Gradle plugin configures which application code should be scanned to generate Terraform code, and all the other necessary information for your deployment.

By scanning your application, the Gradle Kotless plugin can determine a lot of the Terraform code that is required for your deployments. This greatly decreases the amount of deployment config that you have to write yourself, and the things that you do have to write, you can write in Kotlin.

Seamless serverless

Another advantage of Kotless is that you can write your serverless applications like a normal application. Then when it is time to deploy to the cloud, Kotless will split your application into multiple lambdas.

This means that you can deploy the same application as a standalone app in-house, or as a serverless app to the cloud.

Kotless code analysis

By analyzing your application code, Kotless can automatically configure the following things in your cloud environment:

  • API interactions - based on annotations like @Get
  • Events handling - based on the @Scheduled annotation
  • Permissions requirements
  • Queueing systems - based on usage of Queue and List types
  • Calls of other serverless apps - based on async {...}

Conclusion

Kotless looks like a promising framework to make it easier to deploy serverless applications. It already has quite some interesting features, but they are working on it to make it even better!


What the F(p) is Kotlin? by Shelby Cohen and Katie Levy

Used libraries

Shelby Cohen Katie Levy

Shelby Cohen and Katie Levy shared with us the story of how they managed to introduce functional programming with Kotlin into their organisation.

Used libraries

They presented an 8-step guide on how to influence colleagues and your company to adopt Kotlin based on their experience at Intuit:

1. Find your Passion

Find something you want to be passionate about. In this case, it is Kotlin.

2. Socialize

Share your passion with other people. Try to find some things you like about Kotlin - or anything new for that matter - and tell about it to your colleagues. Give some examples on how Kotlin removes ceremony compared to Java. Spread the word on how Kotlin has null-safety built into the type system.

3. Proof of Concept

Do not only talk about your passion. Do as you preach and have something to show to your peers. Develop a new feature and have it reviewed and discussed by the others. This should power the discussion with seniors developers and architects on whether the new technology should be adopted, put on hold or avoided. Having a POC and other developers on board helps this conversation.

4. Create a Plan

The light is green and you are allowed to make the switch. But other developers will still feel insecure about their Kotlin skills. Katie and Shelby put together a plan to migrate from Java. They provided online training courses to teach some basic features which helped the onboarding. This increased the comfort and confidence of the team to make the jump.

By setting goals, they were able to switch at a comfortable pace:

  • Start with migrating and writing Kotlin tests which do not impact production code
  • Migrate easy wins such as data classes
  • Only then start adding new features in Kotlin

They also monitored what their changes were doing to the stability of the product:

  • Less crashes because of the improved type system (less NPEs)
  • Features were written faster in Kotlin
  • Less lines of code (to maintain and read)

Try to provide feedback but watch out to not push learners too much. Some Kotlin code will look a bit Java-y at first, but this will improve over time.

5. Persuade with Data

The other engineers on the team might not (yet) share your passion for Kotlin, so use some data to persuade them even more. Some numbers that can be used:

6. Deconstruct Myths

Even with all this data, there are still some myths that exist concerning the language which you do not want to see spread around. Shelby and Katie broke down these myths in a technical white paper which they talk about on Medium. During the closing keynote of the conference, Maxim Shafirov (Jetbrains’ CEO) also proposed to make an official white paper to help companies migrate.

7. Can’t stop, Won’t Stop

At this point, the team was on board and the train started going full-speed. This is when they started a learning community to get other teams on board to spread the word. They would give presentations, do live coding and code reviews to help others get started too.

8. Connect with Larger Community

Kotlin has an amazing community, which allows you to grow even further. Katie mentions working on an Intuit OpenSource project, attending conferences and podcasts.

Why Functional Programming

Functional programming is a programming paradigm where computations are treated as mathematical functions. Shared state and mutable data are avoided which improves the quality of the codebase. It is also very helpful for multi-threaded workloads. Functional programming is easier in Kotlin because functions are so called first-class citizens. A good third party library which enhances the functional capabilities is arrow-kt.io. It is similar to the Vavr library for Java developers but with the benefits of the Kotlin idioms.


Your First Server with Ktor by Big Nerd Ranch

Big Nerd Ranch

This was a workshop on trying out Ktor and serves as a nice introduction to the framework.

Before starting, it is required that you install the IntelliJ Ktor plugin via the Plugins menu. After doing so, you can start a new Ktor project from within IntelliJ. An alternative way of doing so is by going via the Ktor Project Generator. Something worth noting is that the application.conf file is written in HOCON.

The instructions of the workshops together with the TXT file that is supposed to be read during the exercises can both be found on Google Drive. You will learn how to set up your IDE, starting your Ktor application, and routing and serving data.

New product announcement by Hadi Hariri, Maxim Shafirov and Maarten Balliauw

Intro At the end of the first day it was time to announce JetBrains’ newest product! Maxim Shafirov

Everything started with a ticket created 15 years ago by Maxim Shafirov, the CEO of JetBrains. The ticket was about a request to improve collaboration between teams.

Ticket CEO

Maxim shortly went over how JetBrains came to be. 20 years ago, three developers came together and created a product to help them refactor some code. By now, JetBrains has created over 20 products based on their own needs. During the growth of the company from three developers to 1.200 people, JetBrains faced many challenges on working together between all the different teams.

Creating a product involves more than just a development tool. You have to take several things into account like version control, chat applications for communicating, write documentation and issue tracking. Besides developers, you have other teams within a company such as testers, HR and marketing. A challenge many companies face is to efficiently have all teams cooperate with each other which is why JetBrains wanted to create a tool specifically for this.

Meet Space!


Space is an integrated team environment that provides teams and individuals all tools necessary to create and collaborate efficiently in software development.

Look and feel

Maarten Balliauw

Demo time! Maarten Balliauw demonstrated how Space can be used within a company and gave us an impression on the look and feel.

Look and feel

At the end of the demo, Maxim returned to share the prices of the different subscriptions. Note that a free version is available!

Prices

On the website you can request an invite to try out Space. Attendees of KotlinConf have a guaranteed spot to try it out. More info is available in the blogpost on JetBrains’ website. We think that JetBrains is very ambitious with Space but given how good their products have been until now, we are convinced that this will make another great product.

Rewatch the Space announcement video:


After the announcement, the KotlinConf party started with different types of food, drinks and nice music for all the attendees.

Party

Day Two

The Shuttle Case by Stephen Carver

Stephen Carver The second day was kicked off with another keynote given by Stephen Carver, Senior Lecturer, consultant and speaker in Change and Crisis Management at Cranfield University School of Management. One of the topics of the keynote was risk management and Stephen started talking about NASA.

In 2003 there was the accident with the Space Shuttle Columbia exploding during atmospheric entry causing the death of all seven crew members.

1986 accident

Another similar accident happened in 1986 with the Space Shuttle Challenger. NASA knew this would happen beforehand. They knew about this and let this happen instead of dealing with the change culture, causing human lives to be lost needlessly. People just didn’t listen. It is the fault of the culture and the system.

Stephen said that stories are vital for leaders and that a story expresses how and why life changes and how it can be. He mentioned the following quote:

I believe that this nation should commit itself to achieving the goal, before this decade is out, of landing a man on the Moon and returning him safely to Earth. - John F. Kennedy, May 25, 1961

“By the close of this decade”, quite an ambitious target.

Russians in space

Stephen went over the space progress of the Soviet Union and how the space race came to be between them and the Unites States. The Soviet Union launched the Sputnik 1 into space, the first satellite. There was Laika, the first dog that made it to space in the Sputnik 2. We had Yuri Alekseyevich Gagarin, the first human to make it into outer space and Valentina Tereshkova, the first woman in outer space. And finally there was Alexei Leonov who was the first human to do a spacewalk.

Next up was the Moon landing of the Apollo 11 and the importance of planting the US flag by Neil Armstrong and Buzz Aldrin. Stephen also mentioned the Apollo 13 movie and he recommended watching it some time. He showed a clip of the energy drain part and that they needed to conserve maximum energy in order for the crew to make it safely back to Earth.


Failure is not an option.

More Moon landings followed and to put it in a blunt way, people were getting bored. So what was supposed to be the next thing…? Commercial spaceflights, only this time the cost would need the same considerations as weight safety and performance.

However, NASA was getting old. There was too much management, too little leadership, silos, politics and management by fear. With the Space Shuttle Columbia, it was about getting the weight of three times the Statue of Liberty into space with all the fuel needed.

The solid rocket boosters, also called “white tubes”, were responsible for granting the space shuttle enough trust during the first few minutes of flight. However they were always very fragile seeing as about one out of 20 explode during launch. They were made in Utah and they had to go to Cape Canaveral. Each one of them was about 40 stories high so moving them was quite challenging as they had to be moved in pieces.

Roger Boisjoly

In 1981, the first Space Shuttle Columbia was launched. Given the odds, NASA got very lucky.

Flights continued until 1986 when the temperature was very low, about 25ºF (-4ºC). Icicles were actually hanging off the Space Shuttle Challenger the day before the fateful launch.

Months before the launch, Roger Boisjoly, an American mechanical engineer, raised his concerns and objections to not have a launch in low temperatures like this as the O-rings on the rocket boosters would fail. The management had no ears to this and Boisjoly remained ignored.

After the flight got confirmed for the 28th of January 1986, Boisjoly and his colleagues tried to stop the flight. This was discussed with Morton-Thiokol managers who agreed that the issue was serious enough and NASA got called. NASA went crazy and told them to prove it to them that it was going to blow up. In the end, NASA overruled their warnings and the flight continued.

It was clear beforehand that the O-ring system was going to fail. First O-ring failed upon ignition and a second one failed during throttle up. Moments later the vehicle got disintegrated. The crew actually survived the explosion as they were in a separate crew compartment, but they could not move and knew they would die by falling into the ocean at huge speed.

In 1992, NASA got a new CEO, Daniel S. Goldin, who remained there until 2001. With his “faster, better, cheaper” approach he wanted NASA to continue delivering a wide variety of aerospace programs with costs being cut. He got told it was going to impact on safety but he did not believe it and replied that it was nonsense.

In 2003 there was the Space Shuttle Columbia Disaster. During the launch, a piece of foam insulation broke off from the external tank and struck the left wing of the orbiter, breaking off multiple tiles. NASA managers were aware that this happened but didn’t inspect the damage nor did they inform the crew as they thought that the foam could not have caused a lot of damage. Some engineers suspected that the damage was more serious.

We did not believe pictures would be useful to us, we felt that we could have done nothing anyway so we decided not to even take them. - Ron Dittemore

According to the CAIB Report Appendix D.13 a rescue mission was challenging but entirely feasible to save the crew. However, NASA had the Columbia return to Earth and as it re-entered the atmosphere, the damage done to the left wing caused hot atmospheric gases to penetrate the heat shield and destroy the internal wing structure. This caused the spacecraft to become unstable and break apart, killing the crew of seven.

In 2011 the shuttle program got shut down because the software programs got unreliable and the programmers that made it during the 60’s were either retired or dead.

Gene Kranz vision

Stephen started talking about Elon Musk and his SpaceX company that got founded in 2002.

Elon Musk

What was remarkable was Musk’s persistence and the way he sets his mind on things.

Failure is an option here. If things are not failing you are not innovating enough. - Elon Musk

He even had a small video made of all the different failures they had.


During an interview with Musk, the interviewer mentioned that Musk received criticism from Neil Armstrong and Eugene Cernan. Both of them were heroes to him so it was a painful thing for him to hear them say. He would invite them over to come visit him to see how work was done at SpaceX.

Musk’s successes came one after the other:

Stephen asked the audience who had heard about Blue Origin. About 10% of the people in the room raised their hands. This is obviously the space company of Jeff Bezos. Stephen explained that Bezos puts about $1 billion of personal budget each year into Blue Origin and that giving anything of it away during his divorce was out of the question for him.

With Musk and Bezos, we now have a second space race happening. Two of the richest men of the world, racing to the Moon by 2024.

Takeaway

To conclude, Stephen asked the audience who would have joined the last successful flight of the space shuttle in 2011 if they were given a ticket for it. About 5% of the people raised their hands.

Some of you are mad… and it’s not necessarily the 5% that raised their hands.

Last thing Stephen wanted to give us was the importance of trusting your own intuition.

And the trouble is, if you don’t risk anything, you risk even more. - Erica Jong

All in all, a very strong keynote to start the second day of the conference. We loved it!


The state of Kotlin support in Spring by Sebastien Deleuze

Used libraries

Sébastien Deleuze Big kudos for Sébastien Deleuze for thinking about the environment. He took a train from France to Copenhagen to lower his CO2 emissions. Even though his train got hit by a boar, he still managed to give us an update about the current state of Kotlin support in the Spring ecosystem.

Used libraries

Why Kotlin for Spring?

Sébastien explained that Kotlin has less noise than Java. It gets to the point a lot better and has better (null-)safety. He also considers Kotlin to be more fun in general. Kotlin also has a lot of traction in the Android ecosystem, which might end up influencing and changing the server world.

Spring ♥️ Kotlin

Starting from Spring 5.2, all the Spring Framework reference documentation now has Kotlin code examples.

Used libraries

The new examples are no simple cut and paste from Java but also take into account the Kotlin idioms and DSLs. Extending the reference documentation for Spring Boot and Spring Security are estimated for next year. The Spring Data documentation might take a little longer as it is a rather big project.

Since a few months, the Spring Initializer project also supports Gradle with Kotlin DSL. Kotlin allows for nice DSLs which gets reflected in the number of new DSLs in Spring:

  • MockMVC DSL by Clint Checketts and JB Nizet
  • Spring Cloud Contract DSL by Tim Ysewyn
  • Spring Security DSL by Eleftheria Stein. It is developed by the Spring Security team but still experimental. This will be shipped with the Spring Security library somewhere next year.
  • Spring MVC DSL and functional API. The Router DSL is now available for both Spring MVC and Spring WebFlux.

A quick example of this last bullet point.

@Configuration
class RoutesConfiguration {
    @Bean
    fun routes(): RouterFunction<ServerResponse> = router {
        GET("/hello", ::hello)
    }

    fun hello() {
        ServerResponse.ok().body("Hello, world!")
    }
}

The routes can be created dynamically, which means that routes can be constructed from data. This is handy for webshops or CMS applications in general. The overall Kotlin DSLs’ status is shown in the following picture:

Used libraries

Coroutines

Coroutines

Sébastien stated that coroutines allow consuming the Spring Reactive stack with a nice balance between imperative and declarative style. Coroutines are a new way to consume the reactive stack and have following characteristics:

  • Operations are sequential by default
  • Concurrency is explicit
  • Three Building blocks:
    • Suspending functions are the most important concept and can be used when performing blocking calls such as accessing a database. This is an example of what it would look like:
      suspend fun hello() {
          someExpensiveBlockingCall()
          println("done!")
      }
    
    • Structured concurrency provides building blocks like coroutines scope which define asynchronous boundaries. This is important because it allows to define behaviour for when an error occurs in one of the asynchronous tasks.

    • Flow is the coroutines equivalent of Flux in the Reactor world. It is interoperable with Reactive Streams and has support for back pressure.

Spring Boot

There is now support for loading vals from properties without using lateinit. This means the following code:

@ConfigurationProperties("blog")
class BlogProperties {
    lateinit var title: String
    val banner = Banner()
    
    class Banner {
        val title: String? = null
        lateinit var content: String
    }
}

Can now be re-written using @ConstructorBinding as:

@ConstructorBinding
@ConfigurationProperties("blog")
data class BlogProperties(val title: String, val banner: Banner) {
    data class Banner(val title: String?, val content: String)
}

Kofu: the mother of all DSLs

Kofu is an experimental DSL that allows to define the Spring Boot application configuration. Traditional Spring Boot performs a classpath scan and enables some libraries conditionally (such as Jackson). With Kofu DSL, this is not the case, which allows for a more fine-grained setup. Kofu also allows for a faster application startup and less memory consumption. As it is still experimental, it should not be used in production yet.


Using Kotlin for Data Science by Roman Belov

Roman Belov

While Kotlin is traditionally used for server-side development and Android development, it can also be used to do data science related projects. In this talk, Roman Belov demonstrates what libraries and tools we can use to do data science with Kotlin.

Tools and frameworks

One of the most popular data science tools is Jupyter. Jupyter notebooks are a popular data science tool that allows to easily share code and the resulting output with third parties. It also serves as an interactive shell that allows you to write code and print the output (text, graphs, …) directly underneath it. Jupyter can already be used for Python, R and Scala, and recently Kotlin kernel has been created for this as well.

Roman also shows the integration of Kotlin with Apache Spark, a popular framework for analyzing big data. It is usually used with Scala or Python, but can also be used with Kotlin. He goes on to demonstrate Spark on Apache Zeppelin (a notebook like Jupyter) as well, for which he wrote a Kotlin interpreter. It is also possible to connect to a Zeppelin server in IntelliJ and do most of the things in your favourite IDE instead of on the web-based notebook.

Libraries

Roman demoed the Kotlin Jupyter implementation by using some interesting libraries such as let’s plot and Krangl. Let’s-plot is a library for plotting statistical data. Krangl is used for data wrangling, inspired by the popular dplyr package in R.

Another interesting library in data science is Numpy, used in the Python language. Roman created a library called Kotlin Numpy, a wrapper for the Numpy library. Kotlin Numpy has a couple of advantages over Numpy, such as better performance and type safety.

Conclusion

Kotlin is a general-purpose language, and can thus be used for data science purposes as well. Quite a few interesting libraries have been created by now and are being developed further, making it an interesting alternative for the mainstream data science languages such as Python, Scala and R.


What’s new in Java 19: The end of Kotlin? by Jake Wharton

Jake Wharton

A talk on KotlinConf where the title contains the words “the end of Kotlin” was bound to lure people in. Jake Wharton takes a look into the future to see what features Java could have in 2022, which is when Java 19 will be released, and compare it with the current state of Kotlin.

Variable Type Inference

Java 10 already has type inference for local variables although there are limitations to when you can replace the type with var. Kotlin has no such limitations.

Local functions

Moving on to features that aren’t there yet for Java. In Kotlin you can put a function inside another function, called a local function. This approach allows to reuse code that is only used in the wrapper function, making it clearer that it only belongs to this function. Java will have a similar feature that will probably be in Java 15 or 16.

Multiline Strings

Kotlin allows for multi-line strings with a few options (e.g. trim margin). Multiline strings are currently available in Java 13 (experimental) but will probably be stable in 2020.

fun main() {
println("""
    |SELECT *
    |FROM users
    |WHERE name LIKE 'Jake %'
    |""".trimMargin())
}

Value based classes

Data classes are one of the best features in Kotlin. However, records are coming to Java in the near future, which are similar to data classes in Kotlin. Kotlin also has sealed classes, which can only be extended by classes defined in the same file. Java will have these as well, and will have sealed interfaces on top of that.

Type Matching

To check if a variable matches a certain type in Kotlin, you can use this:

val o: Any = 1
if (o is Int) {
    println(o + 1)
}

Kotlin also has a smart casting system, which automatically casts it to the type you checked for within the code block. Java is getting a similar feature, but without smart casting.

Destructuring

Destructuring in Kotlin works as follows:

data class Person(val name: String, val age: Int)
val alice = Person("Alice", 12)
val (name, age) = alice

You can extract the individual components of the class into local properties. You can also use this in a for each loop (for ((name, age)) in people { }) or on lambda arguments.

Java will also support destructuring in the future, although its usage might be restricted.

Coroutines

Coroutines are a great feature of Kotlin, allowing lightweight asynchronous tasks without starting up new threads. Java might get a similar feature (virtual threads) in the distant future. They will take blocking methods (e.g. Thread.sleep()) and turn them into asynchronous methods.

The end of Kotlin?

While Java might catch up on some features in the future, Kotlin will also evolve in the meantime. On top of that, there are currently no plans in Java to tackle nullability in Java, which is arguably one of the best features of Kotlin. Kotlin also has first-class multi-platform support, which Java doesn’t have (and doesn’t plan to at this point). Furthermore, VM changes and new Java APIs are also beneficial for Kotlin. Finally, Kotlin has IDE support to migrate codebases progressively into Kotlin.

In 3 years, is this going to be the end of Kotlin? I don’t think so. - Jake Wharton


Kotlin in Space by Maxim Mazin

Maxim Mazin

At the end of the first conference day, JetBrains announced their new collaboration tool, Space. Maxim covered how they’ve been using the tool themselves at JetBrains.

Space is actually full-stack Kotlin. There is a shared Kotlin model: data models, view models, validations, RPC, utils and common libraries. Basically everything besides the UI, as it was always an important factor to have it look native, and the storage is shared.

Clients, server, DB

Used frameworks

Used libraries

Exposed allows you to have type-safe SQL and ORM. Initialize your database in an easy way and have it track your model to help you with migration scripts. You define entities that map to tables, for example EUser.

Ktor provides asynchronous servers and clients. It makes it easy to initialize and run a server from code. You specify routes in a simple way based on a path and a suspend code block. There is also WebSocket support. The onConnect, onMessage, onClose and onError are all implemented in a single flow thanks to Coroutines instead of having to implement separate methods.

Kotlin full-stack

Having a Kotlin full-stack architecture makes it easy to check for usages to find dead pieces of code. Within Space there is an administrator playground API to play around with things. OpenAPI (Swagger) JSON is generated in case you want to use something else other than Kotlin.

JetBrains has a GitHub repository kotlin-wrapper that contains a bunch of Kotlin wrapper for popular JavaScript frameworks. kotlin-react, kotlin-css and kotlin-styled are used:

  • kotlin-react: inherit from components and implementing a render function.
  • kotlin-styled: a Kotlin DSL for styled components.
  • kotlin-css: offers type-safe CSS declarations.

Testing

In the backend, the only testing library used besides JUnit is AssertK.

In the frontend, Enzyme is used to test the React components. For UI tests, Selenium is used with Allure for reports with screenshot support in case a test failed.


Going Native: How I used Kotlin Native to Port 6 years of Android Game Code to iOS in 6 months by Ana Redmond

Jake Wharton

Ana Redmond of Infinut presented us with a really nice feel good story about how she made her Android games available for iOS. She noticed her daughters’ faces when they came home with another math assignment. Needless to say, it wasn’t the most happy face. She noticed her kids were trying to memorize the rules instead of really grasping the material. That’s when she realized she could make small games so her kids would not only learn maths better but also enjoy the process.

She created a vast library of over 60 educational games and 120+ lessons for Android devices over a period of six years. Many kids were learning math and enjoying it. Unfortunately, the many kids who use an iPad were left out without access to the material she brought to the Android platform. So when Ana heard about Kotlin/Native she decided the time was right to serve those kids as well!

Kotlin/Native is used to compile Kotlin code to platforms where virtual machines are not desirable or possible, such as iOS. In order to write the individual games once for both platforms, she needed a common interface for the platform specific APIs for drawing on the screen and for playing sound. Luckily, both platforms had very similar APIs for drawing 2D images. The games are then written purely in Kotlin making use of these interfaces. To keep the native experience on both platforms, a few screens, such as the login screen, are still developed using their native platform.

Architecture

You might be wondering “Why did she go through all the trouble to create a multi-platform 2D game engine from scratch when there are many alternatives available?”. Well, you’re lucky. She already addressed this before we had the chance to ask!

There were two big reasons why she did not opt for the Unity game engine, which is an industry standard for making small-scale, multi-platform games. The first reason is that the games would drain much more battery on their target devices. Teachers who employ tablets with these educational games in the classroom were very happy to hear that Infinut’s math games are much more battery-efficient. Another reason is that while Unity is great for rapidly building a game, it is not as easy to build a library of games with shared codebases. The fruits of her labor proved successful as she was able to port her 60+ Android games to iOS using 80% shared code!

There are two ways how Ana used shared code for leveraging platform specific APIs. One way is to make an interface in Kotlin/Native and implement it separately for each platform. The preferred way is to make use of expect and actual to call the native APIs from Kotlin. This way you don’t need to write a wrapper for functionality that is already supported. This method was used for implementing drawing images, playing sound, fonts and transformations.

Two ways of sharing code

Since the back button works differently in Android and iOS, she had to fall back on using an interface. The back button exits the game and returns to the View or Activity in Android or the Controller in iOS to clear everything up. In the code of her game she then just has to write gameplayer.back() which will call the correct implementation depending on the platform. She then stumbled on memory leaks in iOS because of a cyclic reference. This was easily solved using a weak reference.

In the process of porting her 60+ games to Kotlin she learned some valuable lessons.

  1. Don’t use mutable objects
    Using a mutable Singleton, like the SoundManager from the example, led to threading issues as only immutable objects can be shared among threads.
  2. Use List instead of Array
    This is because the Array in Swift works like a List. So wherever Kotlin code is called from Swift code, it’s better to use List instead.
  3. Initialization order
    Something strange happens with parent-child classes where the parent uses a function to initialize the child in an init block which the child overrides and sets a property of the child class. Ana discovered a situation where a property is overridden as expected in Android but not on iOS. This was caused by the initializations of the child class being run in a different order. She recommends not creating child classes this way and to just use the init blocks for initialization. Because she already had a lot of code written in the above way, she opted to just move the property from the child class to the parent class.

More details can be found on her 12-part Medium blog post series.


Summing it all up

There was a good variety of interesting talks to choose from. The first keynote gave a nice overview of the current status of Kotlin whereas the second keynote really got you pumped for the second day of the conference. Noticeable was how much focus was spent on providing healthy food options and snacks. Bella Center Copenhagen was a beautiful venue to host the conference at. It was roomy enough for all the participants and it was convenient having a hotel room in there.

All in all, we had a great time and picked up quite some things. Definitely worth another visit!

KotlinConf photo collage #2

Resources

Yannick is a principal Java consultant and practice manager at Ordina Belgium. He’s passionate about everything Java, Spring and cloud related as well as reactive programming, Kotlin, Lightbend technologies, software architectures, and coaching and enabling other colleagues.

Jeroen is a Java Developer at Ordina Belgium who is passionate about security, breaking stuff and fixing things.

Pieter Van Hees is a Java Software Engineer at Ordina Belgium. He is passionate about Domain-Driven Design and producing clean software that works

Jens is Java Developer at Ordina Belgium with a keen interest in frontend development as well. He’s always up for learning new technologies and is passionate about writing quality tests.

Michael is a Software Engineer at Ordina Belgium with a passion for Android. Besides mobile apps he also enjoys working on backend as well as frontend applications. He is always keen on trying out new things! In his spare time he likes to develop (and play) games.