Auto Added by WPeMatico

Useful Kotlin Idioms You Should Know

Kotlin was designed to be very similar to Java to make migration as smooth as possible. However, Kotlin was also designed to improve the developers’ experience by providing a more expressive syntax and a more sophisticated type system. To take full advantage of the language and write more concise code, learning Kotlin idioms is a must. Without them, it is easy to fall back into old Java patterns.

So, where do you begin? In this blog post, we would like to highlight some good places to start on the path to learning idiomatic Kotlin.

Data classes

Let’s start with data classes, which are probably one of the most popular features of Kotlin. 
If you need a class to hold some values, data classes are exactly what you need. The main purpose of data classes is to hold data, and some utility functions are automatically generated for them.

data class Figure(
   val width: Int,
   val height: Int,
   val length: Int,
   val color: Color,
)

In addition to equals(), hashCode(), and toString() functions, data classes include a very convenient copy() function and a way to destructure the object into number of variables:

val figure = Figure(1, 2, 3, Color.YELLOW)
val (w, h, l, _) = figure.copy(color = Color.RED)

See how we only redefine the color in the copy function for the figure? This is a nice introduction to the next two Kotlin features – named and default arguments.

Named and default arguments

With default arguments, we can remove the need for overloading constructors or functions. 
For example, let’s say we’d like to create instances of the Figure class from the above example with the default color set to GREEN. Instead of adding a secondary constructor, we can just set a default value for the default color:

data class Figure(
   val width: Int,
   val height: Int,
   val length: Int,
   val color: Color = Color.GREEN,
)

val figure = Figure(1, 2, 3)

When we read this code, it is difficult to immediately figure out what the Figure’s constructor arguments are. What do 1, 2, and 3 mean? The IDE can help us out by rendering the parameter names as hints:

To improve the readability of such code, you can also use named arguments:

val figure = Figure(width = 1, height = 2, length = 3)

In fact, we have seen the use of named arguments with the copy() function for data classes:

val greenFigure = Figure(1, 2, 3) // default color is GREEN
val redFigure = greenFigure.copy(color = Color.RED)

The copy() function arguments have all the default values. When invoking the function you can choose which parameters you want to provide:

... = greenFigure.copy(width = 10)
... = greenFigure.copy(color = Color.RED)
... = greenFigure.copy(width = 15, color = Color.YELLOW)

Expressions

An important thing to keep in mind when starting out with Kotlin after having programmed in Java is that if, when, and try are expressions in Kotlin. All of these expressions return a value. 

For instance, instead of

val weather: String = getWeatherConditions()
var drivingStyle = ""

if(weather == "Sunny") {
   drivingStyle = "Speedy"
} else {
   drivingStyle = "Safely"
}

you can write

val weather: String = getWeatherConditions()
var drivingStyle = if(weather == "Sunny") {
   "Speedy"
} else {
   "Safely"
}

When the conditions for the “if” statement are too complex, it is worth using the “when” expression. For instance, this code looks a bit noisy with “if” expressions: 

val weather: String = getWeatherConditions()
var drivingStyle =
   if (weather == "Sunny") {
       "Speedy"
   } else if (weather == "Foggy" || weather == "Rainy") {
       "Safely"
   } else if (weather == "Blizzard") {
       "Don't drive!"
   } else {
       "Undefined"
   }

But it’s much cleaner with a “when” expression:

var drivingStyle = when (getWeatherConditions()) {
   "Sunny" -> "Speedy"
   "Foggy", "Rainy" -> "Safely"
   "Blizzard" -> "Don't drive!"
   else -> "Undefined"
}

In combination with sealed classes (or enum classes), the “when” expression becomes a powerful tool to make your programs safer.

sealed class Weather
object Rainy : Weather()
object Sunny : Weather()
object Foggy : Weather()
object Blizzard : Weather()

var drivingStyle = when (getWeatherConditions()) {
   Sunny -> "Speedy"
   Foggy, Rainy  -> "Safely"
}

This code does not compile! We have to either add an “else” branch in the “when” statement or cover all the remaining options for the condition.

The issue is that using the else branch would diminish the benefits of using sealed classes in “when” expressions. If the else branch is present, adding the new subclass won’t result in a compilation error and you can miss the places where the specific case is required for the new subclass. In Detekt, for instance, you can configure whether or not the else branch can be treated as a valid case for enums and sealed classes.

apply()

In Kotlin, apply() is one of the five scope functions provided by the standard library. It is an extension function and it sets its scope to the object on which apply() is invoked. This allows executing any statements within the scope of the receiver object. In the end, the function returns the same object, with some modified changes.

The function is quite useful for object initialization. For instance, here’s a nice example from Phillip Hauer’s blog:

val dataSource = BasicDataSource().apply {
   driverClassName = "com.mysql.jdbc.Driver"
   url = "jdbc:mysql://domain:3309/db"
   username = "username"
   password = "password"
   maxTotal = 40
   maxIdle = 40
   minIdle = 4
}

Instead of creating an object variable and referring to it for initializing every single property, we can assign the values within the block to the apply() function. 

The apply() function also comes in useful when working with Java libraries that use recursive generics. For instance, Testcontainers use recursive generics to implement self-typing to provide a fluent API. Here’s an example in Java:

[java]
PostgreSQLContainer> container = new PostgreSQLContainer(“postgres:13”)
.withInitScript(“schema.sql”)
.withDatabaseName(“database”)
.withUsername(“user”)
.withPassword(“password”);
[/java]

To implement the same in Kotlin, we can use the apply() function as follows:

val container = postgres("postgres:13") {
   withDatabaseName("db")
   withUsername("user")
   withPassword("password")
   withInitScript("sql/schema.sql")
}

You can learn about using Testcontainers with Kotlin in this Spring Time in Kotlin episode about integration testing.

Null-safety

When talking about Kotlin’s features and idiomatic code, you can’t get around null-safety. An object reference might be null, and the compiler will let us know if we are trying to dereference the null value. That’s really convenient!

val figure: Figure? = createFigure() // can return null
val otherFigure = figure.copy(color = Color.YELLOW)

The figure.copy() is a potential source of NullPointerException, as the createFigure() function might have returned null. We could validate if the reference is null and then safely invoke the copy() function. 

val figure: Figure? = createFigure()
if(figure != null) {
   val otherFigure = figure.copy(color = Color.YELLOW)
}

// or

val figure: Figure? = createFigure() // can return null

if(figure == null) {
   throw IllegalStateException("figure is null")
}

val otherFigure = figure.copy(color = Color.YELLOW)
[kotlin]



<p>You can imagine that in more complex use cases, this code will become quite verbose and cluttered with null-checks. To remedy this, there are useful operators to deal with nullability in Kotlin.</p>



<p>First, you can use the <a href="https://kotlinlang.org/docs/null-safety.html#safe-calls">safe-call operator</a>:</p>



[kotlin runnable=false]
val figure: Figure? = createFigure()
val otherFigure = figure?.copy(color = Color.YELLOW)

Or, if you would like to signal the incorrect situation, it is possible to use the Elvis operator (?:) as follows:

val figure: Figure = createFigure() ?: throw IllegalStateException("figure is null")
val otherFigure = figure.copy(color = Color.YELLOW)

If the result of the createFigure() function is null, then the Elvis operator will lead to throwing the IllegalArgumentException. This means that there’s no situation when the figure object could be null, so you can get rid of the nullable type and the compiler won’t complain about calling any function on this object. The compiler is now absolutely sure that there won’t be a NullPointerException.

When working with object graphs where any object could be null, you inevitably have to null-check the values.

For example, Bob is an employee who may be assigned to a department (or not). That department may in turn have another employee as a department head. To obtain the name of Bob’s department head (if there is one), you write the following:

val bob = findPerson()

if( bob == null || 
    bob.department == null || 
    bob.department.name == null){
   throw IllegalStateException("invalid data")
}

val name = bob.department.head.name

This is so verbose! You can make this code much nicer by using the safe-call and Elvis operators:

val bob = findPerson()
val name = bob?.department?.head?.name ?: throw IllegalStateException("invalid data")

By using the nullable types in Kotlin, you help the compiler to validate your programs, and so make the code safer. The additional operators, like safe-call and Elvis, let you work with the nullable types in a concise manner. You can find more information about null-safety in Kotlin on the documentation page.

Extension functions

In Java, static functions in Util-classes is a common idiom. ClientUtil, StringUtil, and so on – you have definitely encountered these in your Java projects. 

Consider the following example:

class Person(val name: String, val age: Int)

val person = Person("Anton", 16)
println(person) // org.kotlin.Person@6bf256fa

Because there’s no toString() function in the Person class, this code prints just an object reference value. You could either implement your own toString() function, or define Person as a data class to let the compiler generate this function for you. But what if you can’t modify the source of the Person class (e.g. the class is provided by an external library you have added to your project)?

If you use Java habits, you would probably create a PersonUtil class with a static function that takes the Person class as an argument and returns a String. In Kotlin, there’s no need to create *Util classes, as there are top-level functions available, so it would look something like this:

fun prettyPrint(person: Person): String {
   return "Person{name=" + person.name + ", age=" + person.age + "}"
}

You can use string templates instead of string concatenation:

fun prettyPrint(person: Person): String {
   return "Person{name=${person.name}, age=${person.age}}"
}

Since there’s just one statement in the function, you can apply the expression-body syntax as follows:

fun prettyPrint(person: Person): String =
   "Person{name=${person.name}, age=${person.age}}"

It’s getting better, but still looks quite like Java. You can improve this code by implementing prettyPrint() as an extension function to the Person class. You don’t need to modify the Person class source code for that, as the extension can be declared in a different location than the original class.

fun Person.prettyPrint(): String = "Person{name=$name, age=$age}"

Now you can invoke the new function on the Person class instance:

val person = Person("Anton", 16)
println(person.prettyPrint()) // Person{name=Anton, age=16}

By using the extension functions it is possible to extend existing APIs. For instance, when using Java libraries you can extend the existing classes with new functions for convenience. In fact, a number of functions in the Kotlin standard library are implemented via extensions. For instance, scope functions are a prominent example of extension functions in the standard library.

Summary

This is not an exhaustive list of Kotlin idioms, but rather the basics to help you to get started with learning the idiomatic Kotlin style. Meanwhile, our team is working on collecting more idioms in the official documentation. Recently we published a page with the collection of Kotlin idioms for working with Strings. We invite you to share the Kotlin idioms you find useful either in the comments below or on Twitter by mentioning the @kotlin account.

What to read next:

Idioms in Kotlin documentation

Java to Kotlin migration guide (Strings)

Idiomatic Kotlin from formatting to DSL’s — slides by Anton Arhipov

“Idiomatic Kotlin. Best Practices” in Philipp Hauer’s Blog

Server-Side Development with Kotlin: Frameworks and Libraries

Productive Server-Side Development With Kotlin: Stories From The Industry

Continue ReadingUseful Kotlin Idioms You Should Know

Server-side With Kotlin Webinar Series, Vol. 3

Announcing a new series of webinars about Kotlin for server-side! These will take place between May 27 and June 15. Join the live sessions or watch the recordings later!

In this five-webinar series, our speakers will host step-by-step live coding sessions to show you what kinds of benefits you can get from Kotlin for server-side and its rich ecosystem. Each webinar will include a Q&A session to discuss everything you are interested in with the host and speakers from CUBA.platform (now Jmix), http4k, RSocket, Hazelcast, and Quarkus.

Subscribe to our YouTube channel to stay up to date with all the planned webinars and upcoming videos!

Follow Kotlin on YouTube

May 27, Aleksey Stukalov. Getting the Most From JPA With Kotlin

Aleksey Stukalov is a Solutions Director at Haulmont and a technology geek passionate about developer tooling. Since 2015 Aleksey has led the development of the CUBA.platform (now Jmix) framework used in numerous enterprise projects today.

In this webinar, you will learn how to use JPA in your Kotlin applications. You will also learn many tips and tricks for defining JPA entities and how you can use Kotlin to simplify your work.

May 27, 2021, at 17:00 CEST
Register here: https://info.jetbrains.com/kotlin-webinar-may-2021.html

June 1, Nicolas Fränkel. Spring: From MVC to Reactive

Nicolas Fränkel is a Developer Advocate with 15+ years of experience in consulting. He combines working for Hazelcast with training and book-writing.

You will learn how to migrate a traditional Spring Boot application to its Reactive equivalent, and how to use that to cut your monthly bills. In this demo-based talk, Nicolas will show how to migrate a traditional Spring Boot application that uses WebMVC, Spring Data JPA, and Spring Cache to its Reactive equivalent in a step-by-step process.

June 1, 2021, at 17:00 CEST
Register here: https://info.jetbrains.com/kotlin-webinar-june-2021.html

June 8, Oleh Dokuka. What’s New in Spring Boot With Kotlin

Oleh Dokuka is a Software Engineer who has experience with reactive technologies both as a user and a developer. A Java Champion and co-author of the book “Hands‑On Reactive Programming in Spring 5”, Oleh works on RSocket and improves Project Reactor.

In this session, you will learn how to get started with Kotlin Multiplatform and Spring Boot, and build a client-server application using Spring Boot and Kotlin on the server side and Kotlin/JS to power the client UI in the browser.

June 8, 2021, at 18:00 CEST
Register here: https://info.jetbrains.com/kotlin-webinar-june08-2021.html

June 10, Justin Lee. Quarkus for Kotlin Developers

Justin Lee is a Java Champion and a Kotlin fanatic. He has been programming in Java since 1996 and has worked on virtually every level of the application stack, from database drivers to application servers and front-end interfaces. Justin is currently a Principal Software Engineer working on QuarkusIO at Red Hat.

Justin will show you how Kotlin can be used with Quarkus for building applications in the cloud! Quarkus has radically changed how Java developers approach building applications. But even though Quarkus is an amazing framework for Java microservices, that doesn’t mean that Kotlin has to look in from the outside.

June 10, 2021, at 17:00 CEST
Register here: https://info.jetbrains.com/kotlin-webinar-june10-2021.html

June 15, David Denton and Ivan Sanchez. http4k: Server as a Function

Both of your speakers are GoogleDevExperts and co-creators of http4k: David Denton, Engineering Lead, and Ivan Sanchez, independent software consultant.

This session is a practical introduction to http4k, a functional toolkit for writing Kotlin HTTP applications for Server, Serverless, or Native runtimes. Using the Server as a Function approach, you’ll learn how to take advantage of the uniform client and server interfaces to easily create production-ready HTTP applications with zero magic. You’ll also see how this approach unlocks powerful testing techniques that result in super-fast tests that are both well-factored and simple to write.

June 15, 2021, at 18:00 CEST
Register here: https://info.jetbrains.com/kotlin-webinar-june-15-2021.html

Save the date

Once you’ve registered, we’ll send you a confirmation email with calendar invitations, and we’ll also send you a reminder one day before each of the webinars begins.

All webinars are free to attend and will be recorded and published on YouTube after streaming. Subscribe to the Kotlin by JetBrains YouTube channel to be notified about each uploaded recording.

Learn more about server-side Kotlin

We’ve created a page with lots of useful reference materials about using Kotlin on the backend. Follow the link below for tips, tricks, and best practices, all carefully curated by the Kotlin team.

Go to Kotlin server-side page

Continue ReadingServer-side With Kotlin Webinar Series, Vol. 3

Faire Сase Study: Kotlin Backend for a Disruptive SMB Marketplace

Like most startups, at the beginning of its journey Faire was looking for an efficient solution to base its tech stack on. Having started with Java, a year in, the company started looking for other options, and opted for Kotlin. They now use Kotlin for their Android app and for the website backend, which successfully handles up to 1K requests per second.

The current backend repo has 788,020 lines of code within 6,078 Kotlin files, with roughly 45 engineers actively committing code and more onboarding every week.

We chatted with Jeff Gulbronson, a software engineer who has been with Faire since it was a year old, about Faire and why it chose Kotlin. The key benefits of Kotlin he identified were:

  • Kotlin improves developers’ productivity thanks to its modern language features, and helps avoid common Java mistakes.
  • Interop with Java makes it easy to use existing Java libraries.
  • Easy to get started as a Java developer, making hiring easier.
  • Using Kotlin makes the engineering team happier.

Let’s look at Faire’s journey together with Jeff.


Kotlin is an excellent choice for server-side application development. Go to the Kotlin for server-side page to learn more.


About Faire

Originating in the US, Faire is a wholesale marketplace that aims to help small and medium businesses (SMBs) to compete against the likes of Amazon and Walmart and chase their dreams.

The platform is backed by investors, such as Y Combinator, Sequoia Capital, and DST Global. At the end of 2020, Faire raised 170M at a 2.5B valuation and is now looking to expand into Europe.

Architecture Overview

Faire’s backend monolith is written entirely in Kotlin, as are the new services they create as they seek to replace the old monolith system. They make use of both traditional Java libraries, such as Hibernate for ORM, and Guice for dependency injection, as well as libraries written in Kotlin such as Wire for protocol buffers and OkHTTP for network requests. The architecture is standard – a MySQL database, Redis for caching, and then Amazon’s Simple Queue Service (SQS) to run jobs asynchronously.

When an HTTP request comes in, it hits an external load balancer (an Amazon Elastic Load Balancer).

The request is routed to the Kubernetes cluster, where it arrives at an Nginx instance to see which service to route to.

The code is split into two main groups: web server and worker pods. Web server pods service incoming HTTP requests, and enqueue jobs. The jobs are handled by the worker pods, which also handle recurring tasks such as “Run this piece of code every day at 1 am”.

MySQL is the primary data store, and Redis is used for caching. Faire uses an event-streaming service (Kinesis Firehose) to stream data into their data warehouse.

Why Kotlin?

While Java was a fine language choice, Faire started looking for a programming language that would be more expressive and fix some of its shortcomings. Jeff worked with Kotlin at his previous company and had been exposed to how powerful it is. He suggested trying Kotlin and seeing if it would be a better fit for Faire to replace Java.

Kotlin had full interop with the JVM, behaved similarly to Java, but cut down on the rough edges with features such as nullable types, object keyword, mutable vs immutable collections, and more.

“We decided to switch because we liked the velocity of new Kotlin features, and felt the features available at the time made it worth switching to. The fact that the Java interop is first-tier made it extremely easy to introduce Kotlin to the codebase, as there was little to no risk if we decided to switch back to Java in the future.”

For Faire, Kotlin in many ways came across as a “better Java”, for Faire and they jumped into the migration process.

Java to Kotlin Migration: Challenges and Benefits

The initial commit to add Kotlin was only a few files: one to convert a simple existing Java file to Kotlin, and then a couple of updates to the team’s Maven files to update the build system.

They started the migration process by using the Java-to-Kotlin converter built into IntelliJ IDEA. Automated conversion isn’t perfect and requires some manual work to make the code fluent. There were cases where a Java

Integer

would be converted to a Kotlin

Int

, only for the team to find out that field is in fact nullable (sometimes in tests, other times in staging).

Migration to Kotlin helped to reveal previously made assumptions about the nullability of different variables. In Java, extra validation would have to be added to call-sites to catch and prevent errors; with Kotlin, this work could be delegated by leveraging the type system and relying on the compiler. This resulted in less boilerplate code for null checks and improved quality by eliminating human mistakes.

In early 2018 there weren’t many other companies using Kotlin for the backend, so it was tough to find external resources for specific issues. Faire developers overcame these issues through trial and error. For example, Kotlin leans towards final by default, which in some cases conflicts with how Hibernate works. They eventually learned how to properly integrate with Java libraries and built up best practices, and as more of the code was converted to Kotlin, they saw fewer and fewer NPEs.

“Finally Kotlin let us use a modern language that new hires are happy to use. Really it’s like ‘Java Next’, which I think is the sweet spot for server use cases.”

Today the community generates lots of helpful materials. But when it’s your first exposure to a technology, it can be tricky to navigate them. To get daily access to Kotlin news and discussions join our community Slack.

Favorite features

“Java Interop — it feels weird to call this a feature, but we would not have been able to migrate to Kotlin without it. I was extremely impressed by how thoughtful the language creators were around interop, which with the exception of a few nuances, made it extremely easy to migrate our codebase.”

  • Data classes — data classes were a godsend in terms of debuggability (via
    toString

    ), but also in terms of correctness (via

    equals

    and

    hashCode

    ). On the server, the team is constantly creating small classes to move data around.

  • Type system (including read-only collections) — Java libraries provided some of the features that Kotlin gives first-class support for. One such case is
    ImmutableList

    and

    ImmutableSet

    which are provided by Guava. Another is using the

    @Nullable

    and

    @NotNull

    annotations to document variables. Kotlin puts all of these into the type system with

    List

    vs

    MutableList

    , and

    List

    vs

    List?

    . Having first-class support for these in the type system means the language can offer support for them via the standard library, and it doesn’t feel like they’re hacked on to the language. Simply put, this makes the development experience much nicer and lets the language do more of the work.

  • Lambda expressions and type inference — these deserve a special mention, they are again another godsend for us coming from Java (this was pre-Java 11, so no
    var

    keyword). Passing a function around in Java was a nightmare from a type system perspective, which meant we very rarely did it. And having to declare all types (even though IntelliJ IDEA helped) was a drag. With those two features combined, it feels like we can write the code we want (e.g. pass a lambda to a function to be invoked), as there is Java to resist it with its lack of functional support.

Summary

Converting from Java to Kotlin was fun and easy for Faire thanks to the excellent interop between Java and Kotlin. It also brought an additional advantage to the startup in terms of recruiting. Being able to work in a more modern language was compelling to a lot of the developers. And for many it was a new opportunity to write Kotlin in a production environment. Eventually, Faire found almost all of its developers much happier and more productive.

Continue ReadingFaire Сase Study: Kotlin Backend for a Disruptive SMB Marketplace

Expedia Group: Bootiful APIs With GraphQL and Kotlin

About Expedia

Expedia Group is the world’s travel platform. We help knock down the barriers to travel, making it easier, more enjoyable, more attainable and more accessible. We are here to bring the world within reach for customers and partners around the globe. We leverage our platform and technology capabilities across an extensive portfolio of businesses and brands to orchestrate the movement of people and the delivery of travel experiences on both a local and global basis.


Kotlin is an excellent choice for server-side application development. Go to the Kotlin for server-side page to learn more.


The technology stack at Expedia Group

The JVM is the primary technology stack used by the backend services at Expedia Group. The individual teams can choose their technology stack outside of the JVM, but since most libraries are Java-based, most of the backend stack is JVM-based as well. With the microservice architecture, there are currently hundreds of Spring Boot apps powering various parts of the customer experience.

Some teams within Expedia began experimenting with Kotlin on the server side in late 2017. Thanks to the expressiveness of the language, Kotlin quickly gained popularity among developers, and many greenfield projects started adopting it. Soon after, Kotlin became part of the core technology stack. It has also now become the language of choice for developing the new GraphQL services. Kotlin adoption is growing steadily at Expedia, and it is used to power a number of services including GraphQL, REST, and gRPC-based APIs.

Why Kotlin?

Expedia adopted Kotlin because of its null-safety compiler guarantees, the conciseness of the language, and its full Java interoperability. Interoperability with Java made a gradual Kotlin integration possible without having to fully rewrite applications. Migrating existing Java applications to Kotlin generally followed the path of introducing Kotlin data classes first and then gradually migrating the rest of the source code. Java interoperability also allowed Expedia to easily integrate Kotlin applications with Java libraries and fully utilize the existing JVM ecosystem.

Kotlin Coroutines were a critical factor in the wide adoption of the language. They allow developers to write fully asynchronous code in an imperative way, which leads to more readable and maintainable code. The Spring Framework is used heavily at Expedia, and starting with version 5.2 it introduced interoperability between WebFlux and coroutines. For the engineers at Expedia, this was a game-changer that made it possible to leverage the Spring and Reactive stack in a more imperative way.

GraphQL with Kotlin

GraphQL was created to address the needs of mobile clients – it provides a single API for all the clients to integrate with that allows them to selectively ask for the data they need and that can be modified without breaking any of the existing clients. When Expedia started modernizing its frontend stack, they decided to move toward GraphQL and build a single API gateway to power all frontend applications. In order to streamline the development experience and ensure that the code is a single source of truth for the APIs, Expedia applies Kotlin’s powerful reflection library to generate the GraphQL schema directly from the source code.

“We believe that the ability to generate your GraphQL schemas directly from the source is useful functionality that can benefit the open-source community, so we open-sourced the resulting libraries as graphql-kotlin to help developers run GraphQL in Kotlin.” — Dariusz Kuc, Principal Software Engineer

Over time, the graphql-kotlin libraries grew to provide additional functionality, including a Spring Boot autoconfiguration library that eliminates all the boilerplate code needed to configure and run a GraphQL server. As a result, developers can simply write functions that return data classes, and the graphql-kotlin libraries will automatically convert them to a valid GraphQL schema and start a reactive Spring Boot web application.

At KotlinConf 2019, Dariusz Kuc and Guillaume Scheibel talked about how to utilize the power of Spring Boot together with graphql-kotlin. Watch the video:

The shift to Kotlin Coroutines

Expedia started the development of the new GraphQL services using Spring MVC, which relies on a blocking servlet threading model. While it worked, blocking threads was not the most efficient use of hardware resources. Since GraphQL services return data from some downstream services and data stores, whenever there is a dependency on a slow resource, underlying threads end up blocked as they wait for the data to arrive. Reactive frameworks allow you to process the data in a non-blocking way and are a good tool for approaching this problem.

Expedia’s first attempt with reactive frameworks was with RxJava, which helped to parallelize the downstream calls. While it worked for simple things, there were several issues that arose. Developers attempted to use traditional imperative programming models within the reactive paradigm. They were using incorrect operators or causing some unintended side effects. As a result, due to the different programming models, additional training was required, which slowed down the onboarding process of new developers.

That’s why, when Spring announced full interop between their reactive WebFlux framework and Kotlin coroutines, Expedia quickly switched. Thanks to the imperative programming model of Kotlin Coroutines, it was much easier for developers to learn and use it effectively. Coroutines quickly became the preferred way to write highly performant asynchronous code.

“Thanks to Kotlin’s conciseness and support for imperative programming style for writing fully asynchronous code, the resulting code is much more readable and maintainable. “ — Dariusz Kuc, Principal Software Engineer

Summary

In short, the following features make Kotlin an attractive programming language at Expedia:

  • Conciseness. The expressiveness of the language results in concise code, making it possible to write less code with fewer mistakes.
  • Null-safety. This extra safety feature is built into Kotlin’s compiler, resulting in fewer issues with dereferencing null values.
  • Java-interoperability. The fact that you can leverage the Java ecosystem, with all its frameworks and libraries, is a serious productivity booster! You also don’t have to rewrite the Java application fully in Kotlin – you can introduce Kotlin code gradually into your Java project and migrate slowly.
  • Kotlin Coroutines. These offer an easy way to master the asynchronous code with an imperative programming model. The fact that Coroutines support was added to the Spring Framework made it even easier to take advantage of this feature.
Continue ReadingExpedia Group: Bootiful APIs With GraphQL and Kotlin

DoorDash: Building Scalable Backend Services with Kotlin

DoorDash uses Kotlin for all their backend services and infrastructure. Hundreds of engineers work with Kotlin across a massive system spanning multiple repos.

Two years ago, they made the bold move to split their existing legacy Python monolith into multiple backend services, which they developed in Kotlin. This upgrade resulted in tremendous improvements:

  • Better software performance.
  • Сleaner code.
  • Easier code reviews.

Another great thing about Kotlin is that people coming from Java, Golang, and Python find it really easy to get started.


Kotlin is an excellent choice for server-side application development. Go to the Kotlin for server-side page to learn more.


About DoorDash

San Francisco-based on demand logistics platform DoorDash deals with customers who order food, merchants who prepare food for customers, and “Dashers” who deliver the food to the customer’s door.

By the end of November 2020, DoorDash had achieved $1.9 billion in revenue and it’s one of the most anticipated IPOs in 2020.

“We are serving millions of users every day, delivering their orders with a very intricate, well-knitted solution. Our Kotlin services are handling requests from several complex logistic systems in order to weave together a seamless on-demand food delivery experience for the customers.”

Why Kotlin?

DoorDash had a Python monolith system backend that worked satisfactorily but wasn’t going to keep up with the projected scaling. So DoorDash started to look into the options available for making a more scalable solution.

A special internal committee evaluated the choices available, such as Python 3 (with async IO), Java, Golang, and Kotlin in combination with gRPC to see which would best fit the company’s needs. The performance achieved with Python wasn’t sufficient. Golang performed great but at that time it wasn’t suited to complex business logic. The JVM appeared to be the most attractive landscape in terms of libraries, tooling, and frameworks, but almost all the developers were concerned about Java’s ceremonial constructs and bloated code.

Kotlin looked promising with its clean syntax and support for coroutines. It was easy to read, understand, and maintain. Kotlin also allowed developers with existing JVM experience to draw on their existing knowledge while building on top of solid frameworks that were well-documented and battle-tested.

Building up in the JVM ecosystem

The DoorDash software backend now consists of two types of services: “backend for frontend” (BFF) services that act as stateless proxies, and internal services that run on Kotlin and gRPC and are accessible only through BFF. The BFF uses Kotlin either with SpringBoot or Micronaut. In such a system, gRPC servers are capable of writing end-to-end suspendable code without descending into callback hell. This significantly improves performance.

Kotlin also allowed the team to use the rich Java library ecosystem and build solid services with complete instrumentation and maximum visibility.

The common backend stack means that developers can write shared libraries for services and the BFF. In DoorDash, Kroto+ is used to generate the coroutine-friendly client and server code. Building on top of Netty, they were able to add libraries like Lettuce (for Redis), R2DBC (for Postgres), and Micrometer (for instrumentation). These libraries provide the foundation for out-of-the-box coroutine reactor extensions. There was some work done to glue them together, including adding interceptors, extension methods, and dependency injection, but the ecosystem quickly reached a stable state.

“Writing interoperable code between libraries can get tricky. Thanks to Kotlin’s extensions system, we ended up writing additional extensions to weave these constructs together and still write some delightful code.”

Favourite feature

“Nullability and safety is our favorite feature due to the guarantees it can put on the code. Yes, interoperability with Java might still have some nuances, but as long as you have written your code inside Kotlin it’s a lifesaver (almost all of our business logic is in Kotlin).”

Other favourite features at DoorDash:

  • Extension Functions is a lifesaver and an answer to utility classes. If used right they make code look simpler and more pleasant to read.
  • Data classes are something that POJOs or DTOs (Data Transfer Objects) were always missing. Already having the capability to do

    copy

    and

    equals

    simplifies daily chores that would have been some IDE-generated junk or a Lombok hack.

  • Function blocks that look like bodies. This is probably the most heavily used feature in the DoorDash codebase. From caching to instrumentation, it is easy to write nice, well-indented blocks that look like function bodies instead of callback lambdas.
  • Coroutines are last but not least. At DoorDash there is a deep love of coroutines. Coroutines let you write regular straightforward code and manage the code generation for continuations under the hood. This keeps stack traces simpler for coroutine code, reducing cognitive load.

Summary

With Kotlin, DoorDash was able to achieve its scaling goals and improve overall system performance. Perfect Java compatibility and coroutines were the main reasons behind this transformational success. Kotlin was a good middle ground for people coming from Java, Golang, and Python. It was easy for them to quickly catch up and start writing good, maintainable code in Kotlin.

Continue ReadingDoorDash: Building Scalable Backend Services with Kotlin

Server-side with Kotlin Webinar Series

Kotlin is becoming a language of choice for server-side application development. Null safety, 100% Java interoperability, coroutines, and many other features make Kotlin ideal for backend programming.

We’re launching a series of webinars to help you to learn more about backend development with Kotlin or even try it for the first time.

In the next few weeks, speakers from JetBrains, Google, and Confluent will cover three essential topics of backend development: event stream management with Kafka, running applications in the cloud, and backends with Spring Boot.

Kotlin and Apache Kafka

What’s it about?

Viktor and Anton will demonstrate how Kotlin users can leverage Kafka to handle streamed data. The presentation will include a walkthrough of the internal architecture of Kafka.

Presenters:

  • Anton Arhipov, developer advocate at JetBrains, the company that created Kotlin and IntelliJ IDEA.
  • Viktor Gamov, developer advocate at Confluent, makers of an event streaming platform based on Apache Kafka.

Who’s it for?

  • Software engineers with experience of backend development in Java or Kotlin.
  • Engineers who already use Kafka but want to learn more about the capability of the system, or are considering using it with Kotlin.

When?

December 10, 2020
17:30 – 18:30 CET (8:30 PST).
Visit the web page for additional information and time in your timezone.

Register now

Kotlin and Google Cloud Platform

What’s it about?

In this presentation, you’ll learn how to use Kotlin with your existing Java codebase and how to take advantage of modern features like сoroutines, which provide an easier and more efficient concurrency model. You’ll also learn how to deploy Kotlin apps to Google Cloud.

The webinar is hosted by James Ward, developer advocate for Google Cloud Platform.

Who’s it for?

  • Android developers without previous backend experience.
  • Anyone who wants to know more about the capabilities of Kotlin on server-side and in the cloud.

When?

December 17, 2020
17:30 – 18:30 CET (8:30 PST).
Visit the web page for additional information and time in your timezone.

Register now

Kotlin and Spring Boot

What’s it about?

In this webinar, Ray will walk you through the creation of a Kotlin backend service. You’ll use Spring Boot and Spring Cloud GCP to leverage many of the useful Google Cloud services for database, storage, and observability. Once this is done, Ray will demonstrate how to deploy the service to the serverless Google Cloud Platform, where the backend can automatically scale up the number of instances based on load, or scale down to zero instances when no one is using it.

Speaker: Ray Tsang, developer advocate for Google Cloud Platform and Java Champion.

Who’s it for?

  • Android developers without previous backend development experience.
  • Anyone who wants to learn the capabilities of Kotlin with Spring Boot.
  • Anyone interested in serverless technologies.

When?

January 14, 2021
17:30 – 18:30 CET (8:30 PST).
Visit the web page for additional information and time in your timezone.

Register now

Save the date

Once you’ve registered, we’ll send you a confirmation email with calendar invites, and we’ll send you a reminder a day before the webinars begin.

All webinars are free to attend and will be recorded and published to JetBrains TV after streaming. Subscribe to the JetBrains TV YouTube channel to get notifications about when they are uploaded.

Resources

We’ve created a website about productive server-side development with Kotlin. Check out the page for additional information.

Go to Kotlin server-side page

Continue ReadingServer-side with Kotlin Webinar Series

Server-Side Development with Kotlin: Frameworks and Libraries

It is quite common to use existing frameworks and libraries for backend application development. If we look at most of the popular frameworks in the Java ecosystem, many of them actually support Kotlin out of the box. There are a lot of Java libraries too. You can use these frameworks and libraries in your Kotlin programs thanks to Kotlin’s flawless Java interoperability.


Kotlin is an excellent choice for server-side application development. Go to the Kotlin for server-side page to learn more!


This blog post is partially based on presentation content from the Kotlin 1.4 Online Event. You can watch the full video on our YouTube channel.

Spring Framework

The most popular and feature-rich framework in the ecosystem is Spring. Approximately half of all projects in the JVM ecosystem now use Spring as the framework of choice. The previous blog post about Kotlin for server-side development includes stories from Atlassian and Expedia who use Spring Boot for their projects.

Kotlin is one of the four major themes for Spring Framework 5.x. A number of extensions were added to the Spring core API specifically to provide better support for Kotlin.

In fact, Spring’s official documentation features code samples in both Java and Kotlin. This is very convenient if you’re new to Kotlin, because you can see the code sample in Java and then immediately see its Kotlin equivalent and so understand the idioms faster.

The start.spring.io project generator also supports Kotlin along with Java and Groovy.

The number of Spring tutorials is growing. We recommend that you start with the Building web applications with Spring Boot and Kotlin tutorial.

As support for Kotlin in Spring Framework is being improved, we had the privilege to host Sebastien Deleuze with his presentation about The State of Kotlin Support in Spring at the Kotlin 1.4 Online Event this year. See the video below.

An interesting new addition to Spring is the project Spring Fu. It is designed to configure Spring Boot with code in a declarative way. The Kotlin variety of the configuration DSL looks quite nice:

val app = webApplication {
	logging {
		level = LogLevel.DEBUG
	}
	beans {
		bean<SampleService>()
	}
	webMvc {
		port = if (profiles.contains("test")) 8181 else 8080
		router {
			val service = ref<SampleService>()
			GET("/") {
				ok().body(service.generateMessage())
			}
			GET("/api") {
				ok().body(Sample(service.generateMessage()))
			}
		}
		converters {
			string()
			jackson {
				indentOutput = true
			}
		}
	}
}

This new approach to configuration in Spring promises faster startup times and lower memory consumption, and it is a good fit with GraalVM native image thanks to its reflection-less approach.

Ktor

Ktor is a framework created and maintained by JetBrains. It was built with Kotlin from the ground up. Ktor encourages a minimalistic approach to application design, as you only need to configure the functionality that your project requires. Using Kotlin coroutines, Ktor is truly asynchronous and highly scalable. Ktor also includes an HTTP client that is implemented as a multiplatform library and is widely used in mobile application development with Kotlin.

Our previous blog post covers JetBrains Space and Adobe Experience Platform projects that use Ktor because of its support for asynchronous programming.

At Kotlin 1.4 Online Event, Hadi Hariri gave a presentation about the current state of the Ktor project and its future plans. See the video below.

Here are a few tutorials we recommend for learning about Ktor:

More web frameworks

Of course, Spring and Ktor are not the only frameworks in the JVM ecosystem and there are plenty of other frameworks that you can use with Kotlin. Take a look at Micronaut, Quarkus, Javalin, SparkJava, Vaadin, CUBA, and Vert.x. This is just a small list of the frameworks available. All these frameworks have either code samples in Java and Kotlin side by side or have dedicated tutorials on how to use the framework with Kotlin.

There are also a number of frameworks that are implemented in Kotlin. For instance, http4k, and Hexagon.

Database access

Backend applications often rely on database access. One of the most popular libraries today for working with databases is the Exposed library. It is an ORM framework for Kotlin that offers two levels of database access: a typesafe SQL-wrapping DSL, and lightweight data access objects.

Here’s a very simple example using Exposed:

object Cities : Table() {
   val id = integer("id").autoIncrement().primaryKey() // Column<Int>
   val name = varchar("name", 50) // Column<String>
}

Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

transaction {
   create(Cities)

   val saintPetersburgId = Cities.insert {
       it[name] = "St. Petersburg"
   } get Cities.id

   val munichId = Cities.insert {
       it[name] = "Munich"
   } get Cities.id

   Cities.insert {
       it[name] = "Prague"
   }

println("All cities:")

for (city in Cities.selectAll()) {
   println("${city[Cities.id]}: ${city[Cities.name]}")
}

As you might have guessed, Exposed is not the only library that you can use with Kotlin for database access. You can use jdbi, jooq, JPA with Spring Data, and even just pure JDBC API to access databases from Kotlin code.

Testing

Testing a vital part of application development. JUnit and TestNG are perfectly fine for implementing unit tests in Kotlin. But there are more additional libraries that are great for testing in Kotlin:

  • Spek – a Kotlin-based Specification Testing framework for the JVM.
  • Kotest – a testing library with support for Kotlin multiplatform projects.
  • MokK – a mocking library for Kotlin tests.
  • Kotlin Power Assert – an amazing compiler plugin for Kotlin that enables the diagramming of assert function calls, making diagnosis of test failures a breeze.

Other libraries

Aside from handling HTTP requests and accessing databases, applications are often required to communicate with other services using specific protocols, perform decoding/encoding of data in various formats, and many other things. Here are a few libraries that will be useful for application development with Kotlin.

JSON is the universally accepted standard format for sending data between web servers and browsers. There are awesome JSON libraries available in the Java ecosystem and they are great for use in Kotlin programs too. Jackson and gson are the most popular Java libraries for working with JSON. However, there are also libraries that are implemented with Kotlin from scratch. Klaxon is a good example. Also kotlinx.serialization was recently released and it provides JSON support.

gRPC is a high-performance, open-source, universal RPC framework. Kotlin is now supported by gRPC.

RSocket is also gaining popularity as a protocol for use in building microservices. Kotlin integration was recently added to RSocket.

To work with GraphQL there’s graphql-kotlin library maintained by Expedia Group engineers.

These are just a few examples. In fact, there is a long list of Kotlin libraries maintained by the community where you’re sure to find a library for the task at hand. However, we’d like to point out that, thanks to Java interoperability, it is also possible to use virtually any Java library with Kotlin.

Additional Tools

Code quality is an important topic for Kotlin too! Thanks to the type system, especially null-safety, Kotlin is quite a safe programming language. However, there is still a need for code style checks. That’s the part that is currently implemented via additional tools.

Ktlint is a static code analysis tool maintained by Pinterest. It is a 2-in-1 tool that provides linting and formatting (supported via EditorConfig) for Kotlin code.

Detekt is a static code analysis tool that operates with the abstract syntax tree provided by the Kotlin compiler. It is easy to set up with Gradle and there’s also an IntelliJ IDEA plugin that simplifies configuration.

Generating API documentation from source code is also an important part of software project development. In Kotlin, we can use Dokka for this task. It is a documentation engine for Kotlin. Just like Kotlin itself, Dokka fully supports mixed-language Java/Kotlin projects. It understands standard Javadoc comments in Java files and KDoc comments in Kotlin files, and can generate documentation in multiple formats including standard Javadoc, HTML, and Markdown.

Summary

Kotlin was initially designed as an alternative JVM programming language, meaning that Kotlin can be used anywhere where Java is used. Thanks to Java interoperability, it is easy to use any of the existing frameworks and libraries that are familiar to Java developers. This all greatly simplifies the adoption of Kotlin for application development on the JVM.

The current state of Kotlin support in the ecosystem is at the stage where even big projects and companies are confidently adopting it. You can read about a few notable examples of such projects in the previous blog post, Productive Server-Side Development With Kotlin: Stories From The Industry

Continue ReadingServer-Side Development with Kotlin: Frameworks and Libraries

Productive Server-Side Development With Kotlin: Stories From The Industry

Kotlin was created as an alternative to Java, meaning that its application area within the JVM ecosystem was meant to be the same as Java’s. Obviously, this includes server-side development.

Kotlin has experienced immense growth in the Android ecosystem in recent years. The adoption of Kotlin for server-side development is growing steadily as well. However, the question we often get from companies considering adopting Kotlin for server-side development is “Who else is using Kotlin for this?”.

Companies want to be sure that they are making the right decision when choosing technologies. They are looking for confirmation that other companies are successfully employing these technologies for the same intended purpose.

In this post, we would like to briefly highlight a few companies that have adopted Kotin for server-side development. We hope that this will help you make the decision if you are considering adopting Kotlin for the same purposes.

The blog post is based on the presentation content from Kotlin 1.4 Online Event. You can watch the full video at our YouTube channel.

Why Kotlin?

We are constantly talking to developers who use Kotlin, and we have learned about quite a few companies, big and small, that use Kotlin for server-side development. We’re always interested in finding out why companies are choosing Kotlin, and what benefits they gain from it.

There are a lot of nice features in Kotlin, but we’ll highlight those that the users we’ve spoken with liked the most:

  • Concise syntax. The expressiveness of the language results in concise code. The less code there is to write, the fewer bugs sneak into the final application, and the more maintainable the final code is.
  • Null-safety. This is the Kotlin feature that developers like the most. Kotlin’s type system is aimed at eliminating the risk of null references from code, also known as The Billion Dollar Mistake. This extra safety feature is built into Kotlin’s compiler, resulting in fewer issues with dereferencing null values.
  • Java-interoperability. Interoperability with the host platform is a serious productivity booster! With Kotlin, you can leverage the Java ecosystem, with all its frameworks and libraries. It is also possible to introduce Kotlin gradually into an existing Java project without having to convert all the Java code to Kotlin.
  • Kotlin Coroutines. These offer an easy way to master asynchronous code with an imperative programming model. Coroutines are especially useful for developing high-load server-side applications with a lot of IO operations, as they save a lot of system resources. The fact that Coroutines support was added to the Spring Framework made it even easier to take advantage of this feature for server-side developers.
  • Kotlin Multiplatform. With Kotlin, developers can target different platforms – JVM, JavaScript, Android, iOS, and even native applications. The ability to share code between different applications running on different platforms turned out to be quite a useful feature.

Now let’s take a look at a few examples where Kotlin takes development to the next level.

JetBrains Space: extreme code reuse

You won’t be surprised to learn that we use Kotlin at JetBrains. We use it not only for tools but also for services. JetBrains Space, a team collaboration platform announced at KotlinConf 2019, is built with Kotlin and the Ktor framework. Space uses Kotlin for everything: server-side services that run on JVM, an Android application, an iOS application, the web application, and an IDE plugin.

Thanks to Kotlin Multiplatform, a large portion of the code is shared between all these different applications. In addition to sharing the data model across the UI and server-side code, Space also shares the view model, validation logic, and common libraries. The UI components are platform-specific, however, so interoperability is also important for each platform that Kotlin code targets.

Kotlin Multiplatform

Just to give you an idea of how Kotlin supports development for multiple platforms, let’s take a look at the following example. Suppose there’s a data class that we want to use for multiple platforms (JVM, JavaScript, iOS):

class Holiday {
   val name: String,
   val date: LocalDate
}

The String class belongs to Kotlin’s standard library but not LocalDate. We can specify what class should be used as LocalDate for each platform that the application targets. To do this, in the common module that is shared across different platforms, we declare the LocalDate class by using the expect keyword, assuming that the different modules will provide the real implementation. The actual keyword indicates what type should be used in the platform-specific code:

//commonMain
expect class LocalDate()

//jvmMain
actual typealias LocalDate = org.joda.time.LocalDate

//jsMain
actual typealias LocalDate = Moment

//iosMain
actual typealias LocalDate = NSDate

The code that is not platform-specific can be written just once, in the common module of the project. The common code is then reused by the different modules that target specific platforms.

Kotlin support for multiplatform development is especially popular among mobile developers, who use it to share code between Android and iOS applications. You can learn more about this on the Kotlin Multiplatform Mobile website, and you can read about other companies’ experiences with the technology.

Jira Software: Microservices with Kotlin and Spring Boot

Another interesting example is Atlassian’s Jira. Kotlin is used at Atlassian for developing Jira Software cloud products.

Jira used to be a standalone monolithic Java application that users installed on their servers. However, with the introduction of Jira cloud, the need emerged to decompose the application into multiple services in order to scale it better.

The move to the cloud created an opportunity to update the technology stack, and this is how Kotlin came into the picture. The developers felt happy adopting the language, and with happiness comes a productivity boost! Now they use Kotlin with Spring Boot to implement microservices that power critical user experiences. Kotlin and Spring are used across the entire Jira cloud family — in Jira Software, Jira Service Desk, and Jira Core.

Adobe: going lock-free with Kotlin coroutines for high-load services

The Adobe Experience Platform team shared their thoughts on why they prefer Kotlin for server-side development.

They point out that application backends have evolved from monolithic web containers into a distributed mesh of data-driven applications. These applications have to process a lot of data, receive and send messages, and everything is latency-critical.

In their article, they list the key benefits of using Kotlin for server-side development. Support for asynchronous programming is cited as the most valuable Kotlin feature. Kotlin coroutines are described as “easy to learn”, with the resulting code being straightforward and easy to maintain.

“With Kotlin, we can write code in ‘direct style’ that reads almost like blocking, imperative code.”

The applications are quite I/O-heavy, having to rely on external services like queues, various databases, and other services. And these network calls can easily degrade application throughput. Therefore, Kotlin coroutines were immediately appealing for their use case. Going asynchronous improves overall throughput and consequently saves hardware resources.

The other benefits are the key language features in Kotlin: data classes, the sound type system, null safety, and support for functional programming. Kotlin’s flexible syntax makes it easy to create an internal DSL. This is something that appears to have been quite useful for Adobe engineers, too. They also wrote an article about their experience of building a DSL with Kotlin.

Expedia Group: building GraphQL APIs with Kotlin

Expedia adopted Kotlin because of its null-safety compiler guarantees, the conciseness of the language, and its full Java interoperability. Interoperability with Java made a gradual Kotlin integration possible without having to fully rewrite applications. Java interoperability also allowed Expedia to easily integrate Kotlin applications with Java libraries and fully utilize the existing JVM ecosystem.

Kotlin coroutines were a critical factor in the wide adoption of the language. They allow developers to write fully asynchronous code in an imperative way, which leads to more readable and maintainable code. The Spring Framework is used heavily at Expedia, and starting with version 5.2 it introduced interoperability between WebFlux and coroutines. For the engineers at Expedia, this was a game changer that made it possible to leverage the Spring and Reactive stack in a more imperative way.

Recently, Expedia decided to move toward GraphQL and and build a single API gateway to power all frontend applications. To achieve this, they applied Kotlin’s powerful reflection library to generate the GraphQL schema directly from the source code. The resulting set of libraries, graphql-kotlin, turned out to be quite useful. They were open-sourced and are now hosted on GitHub.

At KotlinConf 2019, Dariusz Kuc and Guillaume Scheibel talked about how to utilize the power of Spring Boot together with graphql-kotlin. Here’s the video:

Summary

In this article we shared a few examples of Kotlin adoption for server-side development. At JetBrains, Adobe, Expedia, and Atlassian, Kotlin powers business critical applications that are highly sensitive to performance metrics. This shows that Kotlin is a mature programming language suitable for developing web applications and services.

Tell us your story!

We would love to hear about your experience with Kotlin for developing server-side applications and share your experience with the community!

Continue ReadingProductive Server-Side Development With Kotlin: Stories From The Industry

Productive Server-Side Development With Kotlin: Stories From The Industry

Kotlin was created as an alternative to Java, meaning that its application area within the JVM ecosystem was meant to be the same as Java’s. Obviously, this includes server-side development.

Kotlin has experienced immense growth in the Android ecosystem in recent years. The adoption of Kotlin for server-side development is growing steadily as well. However, the question we often get from companies considering adopting Kotlin for server-side development is “Who else is using Kotlin for this?”.

Companies want to be sure that they are making the right decision when choosing technologies. They are looking for confirmation that other companies are successfully employing these technologies for the same intended purpose.

In this post, we would like to briefly highlight a few companies that have adopted Kotin for server-side development. We hope that this will help you make the decision if you are considering adopting Kotlin for the same purposes.

The blog post is based on the presentation content from Kotlin 1.4 Online Event. You can watch the full video at our YouTube channel.

Why Kotlin?

We are constantly talking to developers who use Kotlin, and we have learned about quite a few companies, big and small, that use Kotlin for server-side development. We’re always interested in finding out why companies are choosing Kotlin, and what benefits they gain from it.

There are a lot of nice features in Kotlin, but we’ll highlight those that the users we’ve spoken with liked the most:

  • Concise syntax. The expressiveness of the language results in concise code. The less code there is to write, the fewer bugs sneak into the final application, and the more maintainable the final code is.
  • Null-safety. This is the Kotlin feature that developers like the most. Kotlin’s type system is aimed at eliminating the risk of null references from code, also known as The Billion Dollar Mistake. This extra safety feature is built into Kotlin’s compiler, resulting in fewer issues with dereferencing null values.
  • Java-interoperability. Interoperability with the host platform is a serious productivity booster! With Kotlin, you can leverage the Java ecosystem, with all its frameworks and libraries. It is also possible to introduce Kotlin gradually into an existing Java project without having to convert all the Java code to Kotlin.
  • Kotlin Coroutines. These offer an easy way to master asynchronous code with an imperative programming model. Coroutines are especially useful for developing high-load server-side applications with a lot of IO operations, as they save a lot of system resources. The fact that Coroutines support was added to the Spring Framework made it even easier to take advantage of this feature for server-side developers.
  • Kotlin Multiplatform. With Kotlin, developers can target different platforms – JVM, JavaScript, Android, iOS, and even native applications. The ability to share code between different applications running on different platforms turned out to be quite a useful feature.

Now let’s take a look at a few examples where Kotlin takes development to the next level.

JetBrains Space: extreme code reuse

You won’t be surprised to learn that we use Kotlin at JetBrains. We use it not only for tools but also for services. JetBrains Space, a team collaboration platform announced at KotlinConf 2019, is built with Kotlin and the Ktor framework. Space uses Kotlin for everything: server-side services that run on JVM, an Android application, an iOS application, the web application, and an IDE plugin.

Thanks to Kotlin Multiplatform, a large portion of the code is shared between all these different applications. In addition to sharing the data model across the UI and server-side code, Space also shares the view model, validation logic, and common libraries. The UI components are platform-specific, however, so interoperability is also important for each platform that Kotlin code targets.

Kotlin Multiplatform

Just to give you an idea of how Kotlin supports development for multiple platforms, let’s take a look at the following example. Suppose there’s a data class that we want to use for multiple platforms (JVM, JavaScript, iOS):

class Holiday {
   val name: String,
   val date: LocalDate
}

The String class belongs to Kotlin’s standard library but not LocalDate. We can specify what class should be used as LocalDate for each platform that the application targets. To do this, in the common module that is shared across different platforms, we declare the LocalDate class by using the expect keyword, assuming that the different modules will provide the real implementation. The actual keyword indicates what type should be used in the platform-specific code:

//commonMain
expect class LocalDate()

//jvmMain
actual typealias LocalDate = org.joda.time.LocalDate

//jsMain
actual typealias LocalDate = Moment

//iosMain
actual typealias LocalDate = NSDate

The code that is not platform-specific can be written just once, in the common module of the project. The common code is then reused by the different modules that target specific platforms.

Kotlin support for multiplatform development is especially popular among mobile developers, who use it to share code between Android and iOS applications. You can learn more about this on the Kotlin Multiplatform Mobile website, and you can read about other companies’ experiences with the technology.

Jira Software: Microservices with Kotlin and Spring Boot

Another interesting example is Atlassian’s Jira. Kotlin is used at Atlassian for developing Jira Software cloud products.

Jira used to be a standalone monolithic Java application that users installed on their servers. However, with the introduction of Jira cloud, the need emerged to decompose the application into multiple services in order to scale it better.

The move to the cloud created an opportunity to update the technology stack, and this is how Kotlin came into the picture. The developers felt happy adopting the language, and with happiness comes a productivity boost! Now they use Kotlin with Spring Boot to implement microservices that power critical user experiences. Kotlin and Spring are used across the entire Jira cloud family — in Jira Software, Jira Service Desk, and Jira Core.

Adobe: going lock-free with Kotlin coroutines for high-load services

The Adobe Experience Platform team shared their thoughts on why they prefer Kotlin for server-side development.

They point out that application backends have evolved from monolithic web containers into a distributed mesh of data-driven applications. These applications have to process a lot of data, receive and send messages, and everything is latency-critical.

In their article, they list the key benefits of using Kotlin for server-side development. Support for asynchronous programming is cited as the most valuable Kotlin feature. Kotlin coroutines are described as “easy to learn”, with the resulting code being straightforward and easy to maintain.

“With Kotlin, we can write code in ‘direct style’ that reads almost like blocking, imperative code.”

The applications are quite I/O-heavy, having to rely on external services like queues, various databases, and other services. And these network calls can easily degrade application throughput. Therefore, Kotlin coroutines were immediately appealing for their use case. Going asynchronous improves overall throughput and consequently saves hardware resources.

The other benefits are the key language features in Kotlin: data classes, the sound type system, null safety, and support for functional programming. Kotlin’s flexible syntax makes it easy to create an internal DSL. This is something that appears to have been quite useful for Adobe engineers, too. They also wrote an article about their experience of building a DSL with Kotlin.

Expedia Group: building GraphQL APIs with Kotlin

Expedia adopted Kotlin because of its null-safety compiler guarantees, the conciseness of the language, and its full Java interoperability. Interoperability with Java made a gradual Kotlin integration possible without having to fully rewrite applications. Java interoperability also allowed Expedia to easily integrate Kotlin applications with Java libraries and fully utilize the existing JVM ecosystem.

Kotlin coroutines were a critical factor in the wide adoption of the language. They allow developers to write fully asynchronous code in an imperative way, which leads to more readable and maintainable code. The Spring Framework is used heavily at Expedia, and starting with version 5.2 it introduced interoperability between WebFlux and coroutines. For the engineers at Expedia, this was a game changer that made it possible to leverage the Spring and Reactive stack in a more imperative way.

Recently, Expedia decided to move toward GraphQL and and build a single API gateway to power all frontend applications. To achieve this, they applied Kotlin’s powerful reflection library to generate the GraphQL schema directly from the source code. The resulting set of libraries, graphql-kotlin, turned out to be quite useful. They were open-sourced and are now hosted on GitHub.

At KotlinConf 2019, Dariusz Kuc and Guillaume Scheibel talked about how to utilize the power of Spring Boot together with graphql-kotlin. Here’s the video:

Summary

In this article we shared a few examples of Kotlin adoption for server-side development. At JetBrains, Adobe, Expedia, and Atlassian, Kotlin powers business critical applications that are highly sensitive to performance metrics. This shows that Kotlin is a mature programming language suitable for developing web applications and services.

Tell us your story!

We would love to hear about your experience with Kotlin for developing server-side applications and share your experience with the community!

Continue ReadingProductive Server-Side Development With Kotlin: Stories From The Industry

Productive Server-Side Development With Kotlin: Stories From The Industry

Kotlin was created as an alternative to Java, meaning that its application area within the JVM ecosystem was meant to be the same as Java’s. Obviously, this includes server-side development.

Kotlin has experienced immense growth in the Android ecosystem in recent years. The adoption of Kotlin for server-side development is growing steadily as well. However, the question we often get from companies considering adopting Kotlin for server-side development is “Who else is using Kotlin for this?”.

Companies want to be sure that they are making the right decision when choosing technologies. They are looking for confirmation that other companies are successfully employing these technologies for the same intended purpose.

In this post, we would like to briefly highlight a few companies that have adopted Kotin for server-side development. We hope that this will help you make the decision if you are considering adopting Kotlin for the same purposes.

The blog post is based on the presentation content from Kotlin 1.4 Online Event. You can watch the full video at our YouTube channel.

Why Kotlin?

We are constantly talking to developers who use Kotlin, and we have learned about quite a few companies, big and small, that use Kotlin for server-side development. We’re always interested in finding out why companies are choosing Kotlin, and what benefits they gain from it.

There are a lot of nice features in Kotlin, but we’ll highlight those that the users we’ve spoken with liked the most:

  • Concise syntax. The expressiveness of the language results in concise code. The less code there is to write, the fewer bugs sneak into the final application, and the more maintainable the final code is.
  • Null-safety. This is the Kotlin feature that developers like the most. Kotlin’s type system is aimed at eliminating the risk of null references from code, also known as The Billion Dollar Mistake. This extra safety feature is built into Kotlin’s compiler, resulting in fewer issues with dereferencing null values.
  • Java-interoperability. Interoperability with the host platform is a serious productivity booster! With Kotlin, you can leverage the Java ecosystem, with all its frameworks and libraries. It is also possible to introduce Kotlin gradually into an existing Java project without having to convert all the Java code to Kotlin.
  • Kotlin Coroutines. These offer an easy way to master asynchronous code with an imperative programming model. Coroutines are especially useful for developing high-load server-side applications with a lot of IO operations, as they save a lot of system resources. The fact that Coroutines support was added to the Spring Framework made it even easier to take advantage of this feature for server-side developers.
  • Kotlin Multiplatform. With Kotlin, developers can target different platforms – JVM, JavaScript, Android, iOS, and even native applications. The ability to share code between different applications running on different platforms turned out to be quite a useful feature.

Now let’s take a look at a few examples where Kotlin takes development to the next level.

JetBrains Space: extreme code reuse

You won’t be surprised to learn that we use Kotlin at JetBrains. We use it not only for tools but also for services. JetBrains Space, a team collaboration platform announced at KotlinConf 2019, is built with Kotlin and the Ktor framework. Space uses Kotlin for everything: server-side services that run on JVM, an Android application, an iOS application, the web application, and an IDE plugin.

Thanks to Kotlin Multiplatform, a large portion of the code is shared between all these different applications. In addition to sharing the data model across the UI and server-side code, Space also shares the view model, validation logic, and common libraries. The UI components are platform-specific, however, so interoperability is also important for each platform that Kotlin code targets.

Kotlin Multiplatform

Just to give you an idea of how Kotlin supports development for multiple platforms, let’s take a look at the following example. Suppose there’s a data class that we want to use for multiple platforms (JVM, JavaScript, iOS):

class Holiday {
   val name: String,
   val date: LocalDate
}

The String class belongs to Kotlin’s standard library but not LocalDate. We can specify what class should be used as LocalDate for each platform that the application targets. To do this, in the common module that is shared across different platforms, we declare the LocalDate class by using the expect keyword, assuming that the different modules will provide the real implementation. The actual keyword indicates what type should be used in the platform-specific code:

//commonMain
expect class LocalDate()

//jvmMain
actual typealias LocalDate = org.joda.time.LocalDate

//jsMain
actual typealias LocalDate = Moment

//iosMain
actual typealias LocalDate = NSDate

The code that is not platform-specific can be written just once, in the common module of the project. The common code is then reused by the different modules that target specific platforms.

Kotlin support for multiplatform development is especially popular among mobile developers, who use it to share code between Android and iOS applications. You can learn more about this on the Kotlin Multiplatform Mobile website, and you can read about other companies’ experiences with the technology.

Jira Software: Microservices with Kotlin and Spring Boot

Another interesting example is Atlassian’s Jira. Kotlin is used at Atlassian for developing Jira Software cloud products.

Jira used to be a standalone monolithic Java application that users installed on their servers. However, with the introduction of Jira cloud, the need emerged to decompose the application into multiple services in order to scale it better.

The move to the cloud created an opportunity to update the technology stack, and this is how Kotlin came into the picture. The developers felt happy adopting the language, and with happiness comes a productivity boost! Now they use Kotlin with Spring Boot to implement microservices that power critical user experiences. Kotlin and Spring are used across the entire Jira cloud family — in Jira Software, Jira Service Desk, and Jira Core.

Adobe: going lock-free with Kotlin coroutines for high-load services

The Adobe Experience Platform team shared their thoughts on why they prefer Kotlin for server-side development.

They point out that application backends have evolved from monolithic web containers into a distributed mesh of data-driven applications. These applications have to process a lot of data, receive and send messages, and everything is latency-critical.

In their article, they list the key benefits of using Kotlin for server-side development. Support for asynchronous programming is cited as the most valuable Kotlin feature. Kotlin coroutines are described as “easy to learn”, with the resulting code being straightforward and easy to maintain.

“With Kotlin, we can write code in ‘direct style’ that reads almost like blocking, imperative code.”

The applications are quite I/O-heavy, having to rely on external services like queues, various databases, and other services. And these network calls can easily degrade application throughput. Therefore, Kotlin coroutines were immediately appealing for their use case. Going asynchronous improves overall throughput and consequently saves hardware resources.

The other benefits are the key language features in Kotlin: data classes, the sound type system, null safety, and support for functional programming. Kotlin’s flexible syntax makes it easy to create an internal DSL. This is something that appears to have been quite useful for Adobe engineers, too. They also wrote an article about their experience of building a DSL with Kotlin.

Expedia Group: building GraphQL APIs with Kotlin

Expedia adopted Kotlin because of its null-safety compiler guarantees, the conciseness of the language, and its full Java interoperability. Interoperability with Java made a gradual Kotlin integration possible without having to fully rewrite applications. Java interoperability also allowed Expedia to easily integrate Kotlin applications with Java libraries and fully utilize the existing JVM ecosystem.

Kotlin coroutines were a critical factor in the wide adoption of the language. They allow developers to write fully asynchronous code in an imperative way, which leads to more readable and maintainable code. The Spring Framework is used heavily at Expedia, and starting with version 5.2 it introduced interoperability between WebFlux and coroutines. For the engineers at Expedia, this was a game changer that made it possible to leverage the Spring and Reactive stack in a more imperative way.

Recently, Expedia decided to move toward GraphQL and and build a single API gateway to power all frontend applications. To achieve this, they applied Kotlin’s powerful reflection library to generate the GraphQL schema directly from the source code. The resulting set of libraries, graphql-kotlin, turned out to be quite useful. They were open-sourced and are now hosted on GitHub.

At KotlinConf 2019, Dariusz Kuc and Guillaume Scheibel talked about how to utilize the power of Spring Boot together with graphql-kotlin. Here’s the video:

Summary

In this article we shared a few examples of Kotlin adoption for server-side development. At JetBrains, Adobe, Expedia, and Atlassian, Kotlin powers business critical applications that are highly sensitive to performance metrics. This shows that Kotlin is a mature programming language suitable for developing web applications and services.

Tell us your story!

We would love to hear about your experience with Kotlin for developing server-side applications and share your experience with the community!

Continue ReadingProductive Server-Side Development With Kotlin: Stories From The Industry

Productive Server-Side Development With Kotlin: Stories From The Industry

Kotlin was created as an alternative to Java, meaning that its application area within the JVM ecosystem was meant to be the same as Java’s. Obviously, this includes server-side development.

Kotlin has experienced immense growth in the Android ecosystem in recent years. The adoption of Kotlin for server-side development is growing steadily as well. However, the question we often get from companies considering adopting Kotlin for server-side development is “Who else is using Kotlin for this?”.

Companies want to be sure that they are making the right decision when choosing technologies. They are looking for confirmation that other companies are successfully employing these technologies for the same intended purpose.

In this post, we would like to briefly highlight a few companies that have adopted Kotin for server-side development. We hope that this will help you make the decision if you are considering adopting Kotlin for the same purposes.

The blog post is based on the presentation content from Kotlin 1.4 Online Event. You can watch the full video at our YouTube channel.

Why Kotlin?

We are constantly talking to developers who use Kotlin, and we have learned about quite a few companies, big and small, that use Kotlin for server-side development. We’re always interested in finding out why companies are choosing Kotlin, and what benefits they gain from it.

There are a lot of nice features in Kotlin, but we’ll highlight those that the users we’ve spoken with liked the most:

  • Concise syntax. The expressiveness of the language results in concise code. The less code there is to write, the fewer bugs sneak into the final application, and the more maintainable the final code is.
  • Null-safety. This is the Kotlin feature that developers like the most. Kotlin’s type system is aimed at eliminating the risk of null references from code, also known as The Billion Dollar Mistake. This extra safety feature is built into Kotlin’s compiler, resulting in fewer issues with dereferencing null values.
  • Java-interoperability. Interoperability with the host platform is a serious productivity booster! With Kotlin, you can leverage the Java ecosystem, with all its frameworks and libraries. It is also possible to introduce Kotlin gradually into an existing Java project without having to convert all the Java code to Kotlin.
  • Kotlin Coroutines. These offer an easy way to master asynchronous code with an imperative programming model. Coroutines are especially useful for developing high-load server-side applications with a lot of IO operations, as they save a lot of system resources. The fact that Coroutines support was added to the Spring Framework made it even easier to take advantage of this feature for server-side developers.
  • Kotlin Multiplatform. With Kotlin, developers can target different platforms – JVM, JavaScript, Android, iOS, and even native applications. The ability to share code between different applications running on different platforms turned out to be quite a useful feature.

Now let’s take a look at a few examples where Kotlin takes development to the next level.

JetBrains Space: extreme code reuse

You won’t be surprised to learn that we use Kotlin at JetBrains. We use it not only for tools but also for services. JetBrains Space, a team collaboration platform announced at KotlinConf 2019, is built with Kotlin and the Ktor framework. Space uses Kotlin for everything: server-side services that run on JVM, an Android application, an iOS application, the web application, and an IDE plugin.

Thanks to Kotlin Multiplatform, a large portion of the code is shared between all these different applications. In addition to sharing the data model across the UI and server-side code, Space also shares the view model, validation logic, and common libraries. The UI components are platform-specific, however, so interoperability is also important for each platform that Kotlin code targets.

Kotlin Multiplatform

Just to give you an idea of how Kotlin supports development for multiple platforms, let’s take a look at the following example. Suppose there’s a data class that we want to use for multiple platforms (JVM, JavaScript, iOS):

class Holiday {
   val name: String,
   val date: LocalDate
}

The String class belongs to Kotlin’s standard library but not LocalDate. We can specify what class should be used as LocalDate for each platform that the application targets. To do this, in the common module that is shared across different platforms, we declare the LocalDate class by using the expect keyword, assuming that the different modules will provide the real implementation. The actual keyword indicates what type should be used in the platform-specific code:

//commonMain
expect class LocalDate()

//jvmMain
actual typealias LocalDate = org.joda.time.LocalDate

//jsMain
actual typealias LocalDate = Moment

//iosMain
actual typealias LocalDate = NSDate

The code that is not platform-specific can be written just once, in the common module of the project. The common code is then reused by the different modules that target specific platforms.

Kotlin support for multiplatform development is especially popular among mobile developers, who use it to share code between Android and iOS applications. You can learn more about this on the Kotlin Multiplatform Mobile website, and you can read about other companies’ experiences with the technology.

Jira Software: Microservices with Kotlin and Spring Boot

Another interesting example is Atlassian’s Jira. Kotlin is used at Atlassian for developing Jira Software cloud products.

Jira used to be a standalone monolithic Java application that users installed on their servers. However, with the introduction of Jira cloud, the need emerged to decompose the application into multiple services in order to scale it better.

The move to the cloud created an opportunity to update the technology stack, and this is how Kotlin came into the picture. The developers felt happy adopting the language, and with happiness comes a productivity boost! Now they use Kotlin with Spring Boot to implement microservices that power critical user experiences. Kotlin and Spring are used across the entire Jira cloud family — in Jira Software, Jira Service Desk, and Jira Core.

Adobe: going lock-free with Kotlin coroutines for high-load services

The Adobe Experience Platform team shared their thoughts on why they prefer Kotlin for server-side development.

They point out that application backends have evolved from monolithic web containers into a distributed mesh of data-driven applications. These applications have to process a lot of data, receive and send messages, and everything is latency-critical.

In their article, they list the key benefits of using Kotlin for server-side development. Support for asynchronous programming is cited as the most valuable Kotlin feature. Kotlin coroutines are described as “easy to learn”, with the resulting code being straightforward and easy to maintain.

“With Kotlin, we can write code in ‘direct style’ that reads almost like blocking, imperative code.”

The applications are quite I/O-heavy, having to rely on external services like queues, various databases, and other services. And these network calls can easily degrade application throughput. Therefore, Kotlin coroutines were immediately appealing for their use case. Going asynchronous improves overall throughput and consequently saves hardware resources.

The other benefits are the key language features in Kotlin: data classes, the sound type system, null safety, and support for functional programming. Kotlin’s flexible syntax makes it easy to create an internal DSL. This is something that appears to have been quite useful for Adobe engineers, too. They also wrote an article about their experience of building a DSL with Kotlin.

Expedia Group: building GraphQL APIs with Kotlin

Expedia adopted Kotlin because of its null-safety compiler guarantees, the conciseness of the language, and its full Java interoperability. Interoperability with Java made a gradual Kotlin integration possible without having to fully rewrite applications. Java interoperability also allowed Expedia to easily integrate Kotlin applications with Java libraries and fully utilize the existing JVM ecosystem.

Kotlin coroutines were a critical factor in the wide adoption of the language. They allow developers to write fully asynchronous code in an imperative way, which leads to more readable and maintainable code. The Spring Framework is used heavily at Expedia, and starting with version 5.2 it introduced interoperability between WebFlux and coroutines. For the engineers at Expedia, this was a game changer that made it possible to leverage the Spring and Reactive stack in a more imperative way.

Recently, Expedia decided to move toward GraphQL and and build a single API gateway to power all frontend applications. To achieve this, they applied Kotlin’s powerful reflection library to generate the GraphQL schema directly from the source code. The resulting set of libraries, graphql-kotlin, turned out to be quite useful. They were open-sourced and are now hosted on GitHub.

At KotlinConf 2019, Dariusz Kuc and Guillaume Scheibel talked about how to utilize the power of Spring Boot together with graphql-kotlin. Here’s the video:

Summary

In this article we shared a few examples of Kotlin adoption for server-side development. At JetBrains, Adobe, Expedia, and Atlassian, Kotlin powers business critical applications that are highly sensitive to performance metrics. This shows that Kotlin is a mature programming language suitable for developing web applications and services.

Tell us your story!

We would love to hear about your experience with Kotlin for developing server-side applications and share your experience with the community!

Continue ReadingProductive Server-Side Development With Kotlin: Stories From The Industry

End of content

No more pages to load