Pitch for Kotlin — 2022

Pitch for Kotlin

Praveen Manvi
13 min readJan 2, 2022

Kotlin outperforms Java in most of the aspects.

Kotlin is a multi-paradigm (object-oriented and functional) language that aims to enable solve software problems efficiently. It is statically typed, meaning, compilation getting many problems without waiting for runtime. Kotlin is a formidable language for JVM developers with highest ROI (with multiplier effect of the code reuse in Web, Mobile, Server, Desktop and Native) compared to alternatives. However Java speeding up with language innovation with faster releases and recent enthusiasm with highly performant ‘Go’ and ‘Rust’, Kotlin deserves a re-look. The writeup articulates the advantages from different stake holder perspective. This comes from experience of execution of multiple projects in Kotlin and also following advancement in this space closely.

What’s for me? Executives

In general manager love metrics and wants decisions are data driven. In general ideas are useless unless used, execution is real value, until then its limbo.

Reduced Project Timelines

Kotlin’s brevity benefits mean the language can solve more problems with fewer lines of code. Kotlin’s concise nature allows developers to read and modify code more efficiently which can reduce a project’s time-to-market. Kotlin products use fewer lines of code compared to Java (30–40% less code). I can assert these numbers from personal experience of building spring boot based micro services. Not only does less code reduce development time, but fewer lines of code also support maintenance needs. There is less surface area for bugs to hide and the enhanced readability of the language makes locating bugs easier for developers, resulting in fewer crashes and system failures.

Fewer App Crashes

Kotlin’s type system is aimed to eliminate the ambiguity of null reference from the code (known as a billion dollar mistake). Anyone who has worked with Java/C++ aware of NullPointerExceptions, they are not only hard forces developers to be as defensive as possible with if(not null) code, especially dealing with code that they don’t have control. Probably Kotlin is the only language that solves this brilliantly.

Last mover advantage

Other than few ideas like null management, extension methods, lambda treatment… most of the ideas were influenced by other languages which is a good thing and advantage for us as we can rely tried and tested concepts. That’s a great win for development team. Jetbrains folks are brilliant at developing IDEs and probably understands developers and their needs than anyone else with 20+ years of experience in this field. Kotlin developers are in safe hands.

Results in more type safe code

Type safe code has real business benefits with reduced maintenance cost. P.S. It works against the lazy developers who love to passing around JSON blobs, or maps of <String,Any>, Its the running cost that’s going to high and no developers love to debug/maintain this type of code and increase in testing cost. Hence its more work for developers in greater common good in a good way of course. It results in attrition safe code.

What’s for me? Python/Go Developers

Modern language constructs that are available in Python/Groovy are available in Kotlin.

Kotlin can get quite close to the compactness of Python’s list/dict/set comprehensions. Since there is huge eco system, we have answers for almost on any topic with single search on web (google, stackoverflow). Most of java solutions are copy paste-able in IDE, Jetbrains working doubly hard along with Google engineers pushing the adoption. Kotlin code feels more pythonic with type safety. The huge difference is not just in line count, but in cognitive overload.

Lets take this python example from REPL,

>>> noprimes = {j for i in range(2, 8) for j in range(i*2, 100, i)}
>>> primes = [x for x in range(2, 100) if x not in noprimes]
>>> print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Kotlin produces the same results with same code semantics and comprehension, as you can notice we need to be explicit being Set (remove duplicates) and use verbs already available with ranges.

>>> val nonprimes = (2..7).flatMap { (it*2..99).step(it).toSet() }
>>> val primes = (2..99).filterNot { it in nonprimes }
>>> println(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

In general working with data structures being type safe it gives Groovy/Python feeling which is great.

Results in more intelligent code

Semicolons, forcing type is archaic. Compilers should help the programmers not the other way round. The more you read/write kotlin it feels intelligent and succinct. As it clearly distinguishes between nullable and non-nullable types, makes code robust and avoid thinking “can it be null”.
Please note that Kotlin will continue to benefit for years of effort of software engineering from JVM which solidified after many experiments over the years namely — “Garbage Collection, Battle tested Libraries and Virtual Machine”. There is no important java library, framework that does not offer Kotlin support as first class citizen. It co-opts well with reluctant java developers side by side.

What’s for me? Java Programmers

First of all Kotlin is Of the Java Developers, by the Java Developers, and for the Java Developers. An essential Kotlin design goal is to create a seamless experience for Java Developers, adding few bits of Kotlin into your existing Java project is a valid approach. Kotlin has incorporated most of the effective java book (probably the best best on java) and makes all these best practices embedded in the language.

Null Safety, Less verbose makes life lot simpler to code. — Tony Hoare, Inventor of QuickSort termed ‘null reference’ as Billion dollar mistake. IMO this itself is good reason for pick Kotlin over java
String Templates makes working with String a breeze with literal that can have embedded expressions.
Singletons — makes it super easy with declaring an object. No circus of private constructors and thread safety issues.
Data Classes — makes lombok, builder pattern un-necessary and ugly
Range Expressions — whole range of options producing super easy readable code.
Operator Overloading — makes code simpler to read.
Implicit Delegation

Functional programming is more convenient, free-standing functions and constants can exists and no class needs to defined.Function definitions can be nested. There is language support for immutable value types (data class) and algebraic data types (Sealed class).

What’s for me? Spring Developers

Largest back end java developers are from Spring eco system. There is no reason to left not to make use of newer Spring reactive framework now a days. Better resource utilisation is good use case for any development. Writing non-blocking web application with Spring WebFlux is quite verbose littered with Mono-s and Flux-es, using the extensions for Kotlin and provided by Spring team (some suspend and Flow), it results compact codebase. As you can see example of swagger api, returning when statement and single statement method.

@Operation(description = "Returns Welcome Greeting on Home Page", summary = "Health check")
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "OK"),
ApiResponse(responseCode = "401", description = "UnAuthorized")
]
)
@GetMapping("/")
suspend fun home(): String = "Hello, Good ${greet()}!. from Kotlin Service."

fun greet(): String {
val hour = LocalDateTime.now().hour
return when {
hour < 12 -> "Morning"
hour < 17 -> {
"Afternoon"
}
else -> "Evening"
}
}

All the async operations and dealing with async drivers and data conversions becomes lot easier and it definitely feels better. The extension feature makes it easy and libraries like mapstruct redundant.

For Ex:

data class Post(
val id: Long,
val title: String,
val keywords: String? = null,
val content: String? = null,
val postedAt: LocalDateTime = LocalDateTime.now()
)

data class PostDto(
val id:Long,
val title:String,
val postedAt: String,
)

fun Post.toPostLineItem(): PostDto =
PostDto(id=this.id, title= this.title, postedAt = postedAt.format(DateTimeFormatter.BASIC_ISO_DATE))
// This is what we will do in controllerfun main() {
val post = Post(id=123, title="Kotlin is Awesome for SpringBoot", keywords = "java,spring,kotlin")
println(post)
println(post.toPostLineItem())
}
/**
Post(id=123, title=Kotlin is Awesome for SpringBoot, keywords=java,spring,kotlin, content=null, postedAt=2022-09-19T13:38:57.054678)
PostDto(id=123, title=Kotlin is Awesome for SpringBoot, postedAt=20220919)
*/

Dealing with same old spring MVC model becomes lot simpler, For ex: statements like ‘model.addAttribute(“kibanaUrl”, kibanaUrl);’ becomes a single line as shown below, as we notice not only we type less but the it’s clear on what is being done.

   /**
* Provides env specific admin application URLs for quick access
*/
@GetMapping("/admin")
fun admin(model: Model): String {
model.asMap()
.putAll(setOf(
"kibanaUrl" to kibanaUrl,
"consulUrl" to consulUrl,
"keyCloakUrl" to keyCloakUrl,
"sbaUrl" to sbaUrl,
))

return "admin/index"
}

What’s for me? UI Developers

JetBrains Compose Multi platform is promising, it’s a declarative framework, so there is no need updating UI logic as backing data changes. This can also be used on desktop with the benefits of hardware acceleration (https://skia.org/) and for web apps, we can now build production-quality dynamic web experiences using Compose for Web’s DOM API, which supports all browser APIs. It allows to share the code between (android, web, server, ios…) multiple application.

Few examples giving glimpse of Kotlin’s power

Here we are adding a quick-sort method to existing List class using extension feature. As you can observe we are also getting top 2 values from sorted values with slice. Kotlin makes collections so simple that libraries like Guava, Eclipse collections becomes irrelevant. As you start coding if you think of some functionality you just typing methods you will be positively surprised to see them :).

https://pl.kotl.in/92846lImL

fun <T : Comparable<T>> List<T>.quickSorted(): List<T> =
if (size < 2) this
else {
val pivot = first()
val (smaller, greater) = drop(1).partition {it <= pivot}
smaller.quickSorted() + pivot + greater.quickSorted()
}

fun main() {
println(listOf(1,4,6,3,2).quickSorted().reversed().slice(0..1))
// Prints [6,4]
}

Adding power with DSL to make java library fluent.

Following libraries should give hint on how fluent with elegant DSL (Domain Specific Language)support is. vaadin-ui , html-dsl , google-kotlin-rpc-support

Here is a simple example on how we can use ‘infix’ to create DSLs.

infix fun <T : Number> T.`%`(percentage: T) = ((percentage.toDouble() / toDouble()) * 100).round()
infix operator fun String.times(repeat: Int) = repeat(repeat)
fun Double.round(decimalPrecision: Int = 2): Double {
return "%.0${decimalPrecision}f".format(this).toDouble()
}
fun main() {
println("Pranav " * 3) // prints 3 times string.
println(180 `%` 174) // prints 96.67
}

Sending email from standard javax.mail library can be fluent and async. Pimp my library pattern (popular with scala) is easy to build with kotlin.

val emailScope = CoroutineScope(Dispatchers.IO + SupervisorJob())

val mailerService = MailerService(
emailScope,
SMTPConfig(
host = "smtp.gmail.com",
port = 465,
smtpSecure = SMTPSecure.SSL,
smtpAuth = true,
username = "auto.emails@examstore.com",
password = "bla bla & bla",
)
)

mailerService.compose().apply {
fromEmail = "auto.emails@examstore.com"
fromName = "From ExamStore Service"
subject = "TEST EMAIL"
to = mutableMapOf(
"praveen.manvi@examstore.com.com" to "Praveen",
"suresh.puvvala@examstore.com" to "Suresh",
"praguna.manvi@examstore.com" to "Praguna",
)
html = "<h1>Hello,<br> message from kotlin emailer service </h1>"
}
.sendAsync()

Working with Concurrency

Kotlin coroutines makes writing parallel code very easy task. Although java evolved with robust library CompletebleFuture, kotlin makes it breeze and structured concurrency (managing hierarchy, inter thread communication, return values, timeouts, cancelations) super easy for developers.

To demonstrate parallelism in Java, Venkat Subramaniam (One of my favourite speaker) shows how to use Java’s ExecutorService and Future APIs to calculate the average price for each minute in parallel. This makes the program run faster.

Now, let’s see how we can achieve the same thing using Kotlin coroutines. Kotlin coroutines are a lightweight, asynchronous programming framework that simplifies concurrent programming. As you can see dealing with Future objects is much easier (async) and parallel code almost looks same as the its serial version & latency is improved by >Nx.

import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis

fun main() = runBlocking {
val service = StockService()
val stockPrices = service.getStockPrices()
val timeTaken = measureTimeMillis {
val results = stockPrices
.map { async { service.getAveragePriceForMinute(it) } }
.awaitAll()
println("Results: $results")
}
println("Coroutine : ${timeTaken}ms")

val timeTakenSerially = measureTimeMillis {
val serialResults = stockPrices.map {
service.getAveragePriceForMinute(it)
}.toList()
println("Results: $serialResults")
}
println("Serially: ${timeTakenSerially}ms")
/**
Results: [105, 110, 115, 120, 125, 130, 135, 140, 145, 150]
Coroutine : 1017ms
Results: [105, 110, 115, 120, 125, 130, 135, 140, 145, 150]
Serially: 10044ms
*/
}

class StockService {
fun getStockPrices(): List<Int> {
return listOf(100, 105, 110, 115, 120, 125, 130, 135, 140, 145)
}

suspend fun getAveragePriceForMinute(price: Int): Int {
delay(1000) // 1 sec to simulate calculation
return price + 5
}
}

Summary

Kotlin is great choice for 2022 and beyond. It has power, community and suitable for server side , mobile , web, data engineering and writing scripts. The availability of vast number of java libraries and developers makes it awesome and sustainable choice for any kind of organisation.

Kotlin delivers well in ‘less with more’ promise. — ‘Succinctness is power’ — 40% less compared to java in most of the cases. Kotlin’s concise syntax(compared to java), which makes it easier to write and read code saving developers time and it also makes difficult to write code that results in null pointer exceptions.
Kotlin is multi paradigm — imperative and functional.
Kotlin coroutines helps to create high-performance asynchronous code easier compared to other languages.
Kotlin allows to intermix with Java code — Its not ‘take it OR leave it’ with java unlike scala
Kotlin allows to create fluent APIs — DSLs
Kotlin has first class support from popular frameworks (Spring, Quarkus)

Will java ever be able to catch up with Kotlin and how about performance of Kotlin compared to Java?

I don’t think so in terms of language features, language & libraries backward compatibility baggage and inability to remove old style of coding will hamper java for ever. This is why even java adds all features available in Kotlin, it will be pulled down by designs like Vector, Properties (Hashtable), Nullability … Sure, Java is moving fast and please note that all its JVM improvements will be available for Kotlin but its language feature all depends on adoptability. java.util.(Date, Stack, Vector) remain as examples bad design. As seen from multiple benchmarks Kotlin offers pretty much the same runtime performance as Java. In many cases because of programming practices (inlining, better structured concurrency with coroutines), it can perform better compared to java as well. In general there won’t become a problem in production that’s unique to kotlin but not available in java.

Is it not difficult to find Kotlin developers compared to java?

True, For maintaining/enhancing large application, java is safe bet anytime. However most of the java developers will become productive (if not proficient) in kotlin in no time. Having gone through scala/groovy hype in the past I can safely claim that kotlin is different and possibly safe and best bet with best in class inter-operability with java and java developers. For green field project running on JVM there is no reason not to use Kotlin. There is learning curve and its worth it. (there is no free lunch anyway).

What the best minds using doing these days?

There is a clear trend of companies having best in class engineers are switching from Java to Kotlin. Examples include but not limited to Uber, Pinterest, Evernote, Netflix, Amazon, Trello, Doordash, Square, Coursera and of course Google;

Some disappointments…

While defining maps, keys and values are paired with the ‘to’ operator, why not ‘:’, I loved groovy, python for this. Kotlin also changed the extends keyword into the : operator. Reversed type declaration i.e. age:Int instead int age was annoying in the beginning, now it’s fine. Missing of package-private visibility modifier felt confusing. Java 17 is already caught up with latest language/JVM improvements. Java 19 getting virtual threads may reduce importance of co-routines, with these most of the touted advantages of kotlin are not relevant. Please note that there are few missing features (compared to java) like “Ternary Operator”, “Static variable”, “Bitwise operators”. Please note there are alternatives to all and there is rationale why they were not included. Data classes (Records), Sealed Classes, Pattern Matching with switch & Multiline strings. New Java’s pattern matching arguably more powerful than Kotlin. Some concerns include what happens if Jetbrains pulls the plug and make it closed? Can they make it more aligned to IDE to sell IntelliJ licenses.

References

https://2024.springio.net/slides/spring-boot-and-kotlin-pain-or-gain-springio24.pdf new addition and probably the best pitch talk on Kotlin.

Server side adoption , why kotlin
Defacto standard for mobile
Kotlin for datascience Khan Academy experiments
https://kotlinlang.org/education/why-teach-kotlin.html

why doordash picked kotlin

https://aws.amazon.com/blogs/opensource/adopting-kotlin-at-prime-video-for-higher-developer-satisfaction-and-less-code/ — amazon prime video

idiomatic kotlin and idiomatic kotlin should help newcomers to join a religion (kotlin here :) ) following standard rituals.

Quick kotlin look up for typescript developers

Quick kotlin look up for python developers

p.md (github.com) -for java script users

java to kotlin — nice to pick kotlin fast for java developers.

https://ttu.github.io/kotlin-is-like-csharp/ — Kotlin C# programmers

Kotlin is Awesome! — Updated to link to look for awesome stuff with kotlin

Coding conventions | Kotlin (kotlinlang.org) & Kotlin style guide | Android Developers & nice summary

https://tibtof.github.io/kotlin-to-rule-dsls/assets/player/KeynoteDHTMLPlayer.html#117 Kotlin is awesome for building rules last slide covers this power in succinct manner.

Lead language designer (now former) andrey breslav brilliant session “shoulders of Giant” what features Kotlin learnt and un-learnt from other languages

Some quotes Kotlin Heroes.

“Languages are often selected by passion, not reason… I’m trying to make Kotlin a language that is loved for a reason.” — Andrey Breslav, Kotlin Lead

“Kotlin is a great language for server-side development because it is easy to read and write, has a concise syntax, and is compatible with Java libraries and frameworks.” — Venkat Subramaniam, Founder of Agile Developer, Inc.
“Kotlin is a game-changer for server-side development. Its clean syntax, null-safety features, and powerful functional programming capabilities make it a pleasure to work with.” — Christina Lee, Senior Software Engineer at Google
“Kotlin is an excellent choice for server-side development because it is a modern, concise, and type-safe language that reduces the likelihood of bugs and errors.” — Ray Tsang, Developer Advocate at Google
“Kotlin has everything you need for server-side development, including great tooling, excellent library support, and a growing community of developers.” — Hadi Hariri, VP of Developer Advocacy at JetBrains

End of the day, language should reduce the possibility of to make wrong choices. It’s not about lines of code. JavaScript, Python2 results in lesser code but TypeScript and Python 3 with type safe code, although results in more code but it will be robust, readable and maintainable and hence are preferred. Kotlin is the best choice by reducing wrong code decisions to creep in. Secret sauce of scalable software is automation, avoiding wrong inputs and maintainable. Kotlin fits the bill well.

--

--

Praveen Manvi

Senior (Architect, Director, VP) Software Engineer. Building web scale SaaS/Multi-Tenant Solutions in Cloud (AWS,GCP,Azure). Ex-Yahoo, Ex-Oracle, Ex-{startups}.