posts
An intelligent
bet for Kotlin.
Part 2

An intelligent bet for Kotlin. Part 2

Dec 4, 2020
The Bored Dev
19.9

The promising Kotlin language has made many developers jump for joy and even rekindled their interest in studying new ways in programming. Staying on top of all things IT, we like to look into what’s working now and how it can benefit the whole community. In the first part of this series, we went through some of Kotlin’s main features, remarking the conciseness, simplicity and pragmatism as bright signs of its identity. We touched upon its various uses, showcasing Kotlin’s versatility and how it provides plenty of options for developers.

Throughout this article, we will discuss some of these features more extensively to have a better understanding of the real benefits that Kotlin could bring. We’re going to see the current impact of Kotlin on the modern industry and what we can expect in the future.

Kotlin and Java: more on features

Let’s dive now into a more in-depth comparison between Kotlin and Java to learn its current state and some of the problems that it might solve.

If you check Kotlin’s releases page 1, you’ll see that it is on version 1.4. So how are Kotlin and Java releases juxtaposed? Are they similar or has something changed recently?

Let’s compare their release cycles in the next timelines.

As you could see in the first timeline, after JDK 9, JDK switched from a feature-based release cycle to a date-based one, with a new release every six months independently of the features’ state. In addition to that, a new LTS version is released every three years.

Kotlin releases also first came out on a feature basis, until JetBrains decided to switch to a date-driven cycle starting from version 1.5 planned for spring 2021. It means that from 2021, both languages will be making more frequent releases regardless of whether new features are ready or still in progress.

If we look closely at the language features, we can notice that Kotlin has supported from the very beginning most of the features that Java is currently trying to bring onboard. Another aspect is that Kotlin now seems to be stable and mature as a language: its releases are more focused on improving performance and developer experience. Java seems to be slowly introducing some features that Kotlin included since its early days; something that I’m calling the “Kotlinization of Java.”

After looking at its main features last time, we could also see that some characteristics are similar to Java. A short learning curve makes Kotlin a good choice for Java developers. Although these two languages are often close, Kotlin repurposes certain nice features like object destructuring from JavaScript or coroutines and channels from Golang, becoming an enhanced programming language by taking all the right parts from different sources.

So, the timelines affirm that Kotlin is paving the way in many aspects, as it has a better understanding of what developers demand from their primary language.

In the first part of this series, I briefly mentioned Kotlin’s coroutines and its different approach for asynchronous programming with respect to Java. Let’s go through it more extensively to understand the big improvements that it brings.

Async programming - Coroutines and Channels

I’ve already mentioned this topic previously, but here we will try to understand why coroutines are so significant. First, let’s discuss the way Java threads work now.

The current implementation of Java threads relies on the OS kernel threads. Two challenges arise:

  1. Threads are very heavy. Mainly because when a thread is suspended, both its native and Java’s call stacks have to be stored or retrieved.
  2. The OS scheduler can’t differentiate threads to group them per user or unit of work. Two threads processing the same data will most likely be executed by different CPUs.

As a result, context switching between threads is expensive and degrades performance due to the high costs of transferring data between CPUs. Ideally, we’d want those two related threads to be processed by the same CPU, but that’s impossible using the OS scheduler. That brings us to Kotlin’s solution to this problem: coroutines.

Kotlin’s coroutines are lightweight components used to run tasks concurrently. Compared to Java Threads, they are tiny in size and managed by Kotlin’s runtime rather than by the operating system. It means we can create lots and have a “thread” per user or transaction, in contrast to Java and its limitations.

How about a coroutines example to understand them better:

val start = System.nanoTime()

runBlocking(Dispatchers.Default) {

   (1..2_000_000).map { index ->

       launch {

           delay(100)

           println("I'm a lightweight thread number $index! running on ${Thread.currentThread()}")

       }

   }

}

println("Done in ${(System.nanoTime() - start) / 10e09} seconds!")

In this example, we are creating 2 million “threads,” each simulating a delay of 100 milliseconds. They will run concurrently, handled by Kotlin’s runtime. Kotlin allows a huge number of threads with no problem at all. This is absolutely not doable in Java. You’d need a limited size thread pool and reuse threads for different invocations as they’re expensive to create and to keep in memory.

Running the code above, we can see that it completes successfully and the heap usage is quite reasonable considering that we’re instantiating 2 million threads:

If we take a look at the actual threads running on our JVM, we can see that despite having 2 million virtual threads, the runtime is using a pool of eight threads or dispatchers.

The way coroutines work simplifies writing asynchronous tasks for developers considerably. First, thread management is hidden behind Kotlin’s runtime, and second, you can write async tasks the same way you do synchronous ones.

The language also provides channels as a way of communication between coroutines. Imagine them as a messaging system: An emitter sends messages to a channel, while one or more receivers process those messages. Coroutines always within a channel.

It’s a much more efficient and more straightforward approach to deal with concurrency and parallelism. Instead of sharing resources, the stakeholders communicate between them to achieve a common goal!

Now that we have a better knowledge of Kotlin as a language let’s see how it is currently doing in our industry.

Its present, a really good start

Judging from the market trends and developers’ comments on social media, the community has received Kotlin with a warm welcome. This language has been a breath of fresh air for many; its radical and intelligent approach has made a big difference.

The image below shows the worldwide interest in Kotlin, according to Google Trends:

Kotlin looks like a completely new language but at the same time has full Java-interoperability and is able to use the JVM as its runtime environment: this is a huge advantage and a smart move for its creators. Among different JVM languages capable of interoperating with Java code, Kotlin’s flawless interoperability is far superior in some cases. When the level of interoperability is similar, other characteristics tilt the balance in favour of Kotlin.

Most enterprises are afraid of big changes. Understandably, they don’t want to get stuck in an uncomfortable situation where every employee dislikes the novelty, the management regrets the decision entirely, and no one sees an easy way of going back.

Kotlin has allowed companies to take small steps, keep using the same libraries and frameworks and slowly move to Kotlin. They can see how things go following a more conservative approach, with no rush and minimal risk.

Although Kotlin allows switching from Java in a smoother manner, it’s worth mentioning that transitioning to a new language in production is never an easy task. You’ll need to set up an appropriate plan with clearly defined goals. It’s crucial to understand:

  • what we want to achieve,
  • why we are making a choice we’re making, and
  • how to take everyone on board, including the management.

Think about what may hinder the migration. These obstacles include a potential lack of experience with the new language or difficulties in bringing new developers into your team. Once the risks are clear, it’ll be easier to prepare, minimise them or even have a backup plan ready.

One important aspect to consider when migrating to Kotlin is that it has become a first-class citizen in the Spring framework after Pivotal (now part of VMware Tanzu) decided to start supporting Kotlin since version 5.0 in 2017.2 This allows using Kotlin features in the Spring integration and experiencing a simpler transition from Java for all projects using Spring.

Another big step in Kotlin’s adoption has been its tremendous success in the mobile app industry. In 2017, Google first announced the Kotlin support for Android development. Then, only two years later, the IT giant publicly stated that its new preferred language for Android development was Kotlin. It means that now everyone can use the same language and the same libraries for backend and mobile applications as we do with Java, but writing a more concise, expressive and elegant code, while also taking advantage of the brilliant language features such as null-safety or coroutines.

As we can see, Kotlin’s present looks bright, but what future lies ahead?

Its future

If someone made me bet for one language in the next few years, it’d definitely be Kotlin.

Visionary language

In our sector, being agile and fast to stay ahead is key to achieving business goals. That’s why betting for Kotlin could become a competitive advantage. The adoption of Kotlin could mean a boost in productivity for the teams in your organisation. Why wait for the next Java LTS release to be able to use some features which are already available in Kotlin? To make things worse, some of the features that we’ve been really missing for years in Java have been supported by Kotlin for years. While they are not even planned in Java’s roadmap for the next releases.

Good examples of these missing features could be Java records: still feature previews, meaning we’ll have to wait at least 6–12 months before using them safely. Or the much-awaited Project Loom. Java Threads have been a pain for a very long time, and still, the work only started in late 2017. Although the OpenJDK community is making good progress and has early-access builds3 available, the project is still far from complete. In contrast, JetBrains managed to have something production-ready in a much more reasonable timeframe. This is one of the reasons why some developers lose their patience with Java and switch to Kotlin.

When writing code in Kotlin, we get all the system benefits of Java as a JVM language, e.g. in terms of performance. Simultaneously, we benefit from one of the nicest syntaxes when it comes to readability.

Usability

We all know that Kotlin’s main uses are server-side and Android development. But what makes Kotlin even more interesting is that it’s been designed as a multiplatform language in a way that goes beyond our traditional understanding of “multiplatformity” from a JVM-world point of view. We can make use of Kotlin/JS to transpile our code to JavaScript, being able to write web frontend applications or even React applications!4 Without going into too much detail, I think that this could bring many benefits to full-stack development and, above all, fill an existing backend–frontend gap and improve things looking forward.

Besides, we have Kotlin/Native to write Kotlin applications on the platforms where running a JVM is not possible or desirable (embedded devices, iOS, etc.) — which may be valuable to specific use cases.

All of this provides increased flexibility for developers, with the added extra of fantastic tooling support provided by JetBrains, a major tooling manufacturer.

Creators and community

But the reasons behind a promising future for Kotlin are not purely technical; they’re also structural and organisational. From my perspective, JetBrains is a fairly small, dynamic and fast-paced company with clear objectives and huge ambitions. It is able to gain the right traction and enough speed to make things happen quickly, which is something big enterprises find very hard to beat. It might be their size that makes them slower or fear of the new, but they can’t compete with JetBrains.

What I see happening in the near future is that Kotlin will keep coming up with features and innovation that will improve the language experience even further. The more developers embrace it in the Open Source community, the faster changes in the JVM world will take place.

JetBrains has proven with their success with IntelliJ IDEA, becoming the favourite IDE among developers worldwide, that they understand developers and their needs. It is and will be the cornerstone in their success with Kotlin as well; know your audience, and they’ll love your product.

We’ve also seen that the number of companies interested in Kotlin or partnering with JetBrains has been growing in the last few years. For instance, BellSoft and JetBrains agreed a strategic collaboration in 2019, in which Bellsoft provides security patches and critical updates to JetBrains runtime, a fork of JRE used in all language IDEs. These are the same updates and the same process as for BellSoft’s own distribution called Liberica JDK. That’s one of the reasons why I’d recommend using Liberica JDK with Kotlin due to their close relationship and collaboration.

I can only see this kind of trend of mutual collaborations become more active and intense in the following years.

Conclusion

In summary, the future of Kotlin will depend on how willing and open-minded the community is to bet for this language firmly. Considering its simplicity and full interoperability with Java, I don’t see an apparent reason not to give it a chance. Kotlin is a language able to improve a team’s productivity and the readability of the codebase. On top of that, it allows migrating gradually and taking minimal risk.

In terms of growth, the dynamic and fast-paced environment provided by JetBrains could be a critical factor in the upcoming years. The company knows developers’ needs and has proven that by building the most popular IDE. This vital experience, combined with a clear determination, might be a decisive factor for a big success of Kotlin in the long run. Who knows, it might be time to break with the past and bet for the future after all!

References

  1. Kotlin Releases.
  2. Introducing Kotlin support in Spring Framework 5.0.
  3. Project Loom Early-Access Builds.
  4. Get started with Kotlin/JS for React.

Subcribe to our newsletter

figure

Read the industry news, receive solutions to your problems, and find the ways to save money.

Further reading