1

Introducing Kotlin

The secret to getting ahead is getting started.

Mark Twain

This chapter provides an overview of the Kotlin programming language, the principles on which it is built, and the benefits it brings compared to Java, with particular focus on writing Android apps. We will also introduce the ecosystem and community around Kotlin and online resources for the language.

What Is Kotlin?

Kotlin is a statically typed programming language that is completely open source and free to use. Kotlin code can compile down to Java bytecode and thus can run on the Java virtual machine (JVM) and on Android.1 Apart from this, it can be compiled down to JavaScript2 and can even run on embedded devices and iOS3 devices. The big picture is to be able to target all these platforms with a single language and share parts of your code base between them. In this book, we focus only on Kotlin targeting Java bytecode, particularly on Android.

1. https://developer.android.com/

2. https://developer.mozilla.org/en-US/docs/Web/javascript/

3. https://developer.apple.com/ios/

Kotlin was developed by JetBrains,4 the Czech software tool company that develops the IntelliJ integrated development environment (IDE), among others. Kotlin was designed to be completely interoperable with Java, meaning that Kotlin code can use any Java classes and libraries and vice versa. Even though Kotlin is very similar to Java in many regards, its language design is much cleaner and uses the expertise that was gained in software development and programming language design since the release of the first version of Java in 1996. For instance, checked exceptions have shown drawbacks for large-scale software (so Kotlin only has unchecked exceptions), Java tends to require much boilerplate code (so Kotlin avoids this), and inheritance comes at the cost of very tight coupling (so Kotlin classes are closed for inheritance by default). In short, Kotlin does not carry much legacy, which allows for a clean language that incorporates best practices from the start.

4. https://www.jetbrains.com/

Goals and Language Concepts

The main goal of Kotlin is to provide a pragmatic, concise, interoperable, and safe programming language.

What differentiates Kotlin from many other modern JVM languages such as Scala,6 Ceylon,7 and Clojure8 is that it focuses on enterprise software and is not an academic endeavor. Instead, it is developed and maintained by JetBrains, who make heavy use of Kotlin themselves to develop their stack of IDEs and other tools.

6. https://scala-lang.org/

7. https://www.ceylon-lang.org/

8. https://clojure.org/

Additionally, when compared to a language like Scala, Kotlin is more lightweight because it is intentionally constrained. There are several reasons for this. First, this improves toolability because fewer language concepts need to be supported by the compiler, IDEs, and other tools. Second, it increases simplicity, thus making the language easier to use and code easier to read for developers. Third, solution paths are constrained, thus making it clearer how to solve a particular problem.

Why Use Kotlin on Android?

At the Google I/O 2017 developer conference, Google9 announced official support for Kotlin as a language for Android app development; it joins Java and C++. This decision was certainly motivated by Google’s lawsuit with Oracle over patents on the Java APIs, but this section focuses on why Kotlin may be preferable to Java from a language perspective.

9. https://www.google.com/intl/en_de/about/

Kotlin can run on the JVM and is fully compatible with Java 6, which makes it a viable language for writing Android apps. Due to its similarity with Java, Android developers can learn Kotlin’s syntax and understand its semantics quickly. This not only means that the effort involved in switching to Kotlin is comparably low, it also means that it entails less risk. Performance-wise, using Kotlin instead of Java comes at no additional cost; the bytecode is executed just as fast as any Java bytecode. Additionally, the Kotlin runtime is fairly small, so it does not add much weight to the application.

Java on Android

To understand how Kotlin fits into the Java and Android ecosystems, we briefly recap the history and current situation for Android app development with Java. We focus on Java 6 and above because that is what is currently relevant for Android.

Java 6 already supports many crucial language features it inherits from Java 5, including generic types, enumeration types, annotations, variable-argument parameters, for-each loops, and static imports. Additionally, Java 6 itself adds significant performance improvements in the core platform, the compiler, and synchronized code. Generally, each language update entails performance improvements, a more robust core platform, and various language enhancements. Therefore, adopting a newer Java version typically improves productivity and allows writing more concise and maintainable code. Unfortunately, this is not always possible if a target platform (or Android device in this case) is not compatible with the desired Java version, which is why Android developers still have to rely mostly on Java 7 at the time of writing.

In order to support at least 96% of Android devices today, you have to target Android 4.4 (API level 19). To reach at least 98% support, Android 4.2 (API level 17) must be targeted; and to support 100% of devices, it is necessary to target Android 2.3.3 (API level 10) from 2010. You can find the latest numbers in Android’s Distribution Dashboard.10

10. https://developer.android.com/about/dashboards/

On any device running Android 4.4 or lower, Android applications are run on the Dalvik virtual machine, which is part of the operating system. Java bytecode is not executed directly but first translated to a Dalvik executable. Since Android 4.4, Dalvik has been replaced by the Android Runtime (ART), which is the only included runtime in Android versions 5.0 and above. Apart from the runtime, which Java features are available also depends on which toolchain is used. For instance, the D8 dexer that replaced DX in Android Studio 3.1 allows you to use some Java 8 features such as lambda expressions. For these two reasons (runtime and toolchain), there is no direct mapping from Android versions to supported Java versions; each language feature may or may not be supported by ART or your toolchain. Over time, additional Java language features become incorporated into Android but with a significant delay. With Kotlin, you can have language features even beyond those from Java 8 today.

Kotlin on Android

When developing apps for Android nowadays, you are mostly tied to Java 7. With Android Studio 3.0 and later, all Java 7 features and several Java 8 features, most prominently lambda expressions, method references, and default interface methods, are available for all API levels. Still, the more devices you want to support, the fewer language features are available and the harder it becomes to write maintainable and high-quality code. In addition, you will always have to wait for new Java features to become supported on Android. For instance, Java 8 Streams only work with API level 24+ at the time of writing, whereas Kotlin’s equivalent Sequences work irrespective of API level.

With Kotlin, you are not tied to any Java version, and you can use all features developers are longing for in Java 8—plus many more. Functional-style programming with higher-order functions and lambda expressions is incorporated from the start in Kotlin. This leads to several syntactic advantages in the language design when compared with lambdas in Java. Powerful APIs for collections and I/O operations in Kotlin supersede what you could achieve with Streams in Java 8, and default interface methods are a part of Kotlin as well.

Kotlin versus Java 8

Java 8 was a huge language update that really changed the way you write code in Java. This is not the case to that extent for every Java language update. For instance, Java 9 mainly changes the way developers package and deploy their code (due to the module system) but not so much how they think about problems and write code. As you may have noticed from the language concepts discussed above, Kotlin has several useful language features that Java 8—and even Java 9, 10, or 11—do not provide. This includes nullable types to provide null safety, comprehensive type inference, extension functions, smart casts, named and default parameters, and more. Most of these can make your code more concise and expressive at the same time; features like these will be introduced in Part I of this book.

With Kotlin, you have a strong standard library at your disposal in addition to the Java standard library, which is also available for use. The Kotlin standard library encompasses many functional-style methods to work with collections and I/O streams, many useful predefined extension functions, and a variety of third-party libraries to simplify working with JavaFX,11 Android,12 databases,13 and more. In this book, you will learn how to use the Anko library for Android app development.

11. TornadoFX, https://github.com/edvin/tornadofx

12. Anko, https://github.com/Kotlin/anko

13. Exposed, https://github.com/JetBrains/Exposed

Tool Support and Community

Kotlin is designed to be highly toolable from its roots. For instance, static typing enables sophisticated refactorings, compile-time checks, and autocompletions. It is not surprising that toolability is not an afterthought in Kotlin, considering that JetBrains is a tool company. IDEs that have strong support for Kotlin include IntelliJ IDEA, Android Studio, Eclipse, and NetBeans. They facilitate writing idiomatic Kotlin code by suggesting better ways to rewrite parts of the code, among other things.

Still, myriad tools, libraries, and frameworks has been developed for Java over the last decades, and not all of them work with Kotlin as smoothly as they do with Java, such as static analysis tools and linters, the build tool Buck,14 or the mocking library Mockito.15 Fortunately, most existing tools and libraries work smoothly with Kotlin, for instance Gradle,16 Retrofit,17 and Android architecture components. On Android specifically, Google is pushing Kotlin-specific APIs, such as Android KTX,18 that help developers write code more effectively.

14. https://buckbuild.com/

15. https://site.mockito.org/

16. https://gradle.org/

17. http://square.github.io/retrofit/

18. https://developer.android.com/kotlin/ktx

There is an active community around Kotlin that acts via various channels in order to give feedback to the Kotlin team and help shape the way the language evolves. The Slack channel19 has very active discussions and is a good place to ask your questions while learning Kotlin. There is also a discussion forum20 that often features more advanced discussions concerning language design decisions and the future direction of Kotlin. Among others, there is also a Reddit subreddit specifically for Kotlin21 as well as various talks about the language. An overview of all community resources is available on the Kotlin website.22

19. http://slack.kotlinlang.org/

20. https://discuss.kotlinlang.org

21. https://www.reddit.com/r/Kotlin/

22. https://kotlinlang.org/community/

Business Perspective

Because the intent is for Kotlin to be usable wherever Java runs, it is important to make the transition easy. Indeed, the effort involved in learning Kotlin is comparably low for developers using Java or a similar language because many language concepts are the same or very similar, such as classes, interfaces, and generics. However, other language concepts may not be familiar to developers using a language without functional programming features, such as lambda expressions and streams. Lastly, some language concepts are not known from most other languages, such as non-nullable types and extension functions.

This is one of the common reasons why adopting a new language always introduces a certain risk. You have to expect a productivity slowdown at least in the beginning of introducing a new language before productivity can finally increase. During this transition time, businesses must also provide the time and resources necessary for the training that developers will need.

Additionally, adoption of a new language is inherently hard to reverse. If you decide to make the transition from Java by converting several Java files from your flagship product to Kotlin and make changes to that code, it will take time to rewrite (or decompile and refactor) this code back to Java. Ideally, try out Kotlin in a noncritical environment such as a pet project to familiarize yourself with the syntax and tooling without introducing unnecessary risk. Chapter 10, Migrating to Kotlin, discusses best practices for adopting Kotlin in detail.

Tooling for Kotlin includes IntelliJ IDEA and Android Studio, where the Kotlin plugin comes with a Java-to-Kotlin converter, which can be used for two main purposes. First, it allows the developer to move a Java code base to Kotlin faster. However, the converted code will typically need manual changes to be free of errors and more extensive work to resemble idiomatic Kotlin code. Second, the converter can be used for learning purposes. Since developers understand their Java code, they can compare that to the Kotlin code generated in order to learn how the different concepts and language elements are mapped to one another. This is another reason why Java developers can learn Kotlin fairly quickly. Remember, you may want to keep a copy of the original Java file.

Once developers are familiar with the Kotlin language, performance can potentially increase significantly due to the possibility to express more with less code and the fact that Kotlin enforces many best practices by design. For instance, correctly using nullable types increases robustness of the code by preventing NullPointerExceptions. Similarly, classes are closed for inheritance by default, thus enforcing the principle to explicitly design for inheritance before allowing it. In total, this leads to a code base that is less prone to errors and costs less to maintain.

Who’s Using Kotlin?

Hundreds of companies have already incorporated Kotlin into their technology stack, from young startups to large corporations. Besides JetBrains and Google, who obviously use them intensively, these include Pinterest,23 Slack,24 Uber,25 Netflix,26 WordPress,27 Udacity,28 Evernote,29 Lyft,30 and Trello.31 Developers from many of these contribute to the Kotlin community by sharing their experiences with the language and what they found to be best practices.

23. https://www.pinterest.com/

24. https://slack.com/

25. https://www.uber.com/

26. https://www.netflix.com/

27. https://wordpress.com/

28. https://udacity.com

29. https://evernote.com/

30. https://www.lyft.com/

31. https://trello.com/

Although Kotlin gained popularity through being an official language for Android development, its goal is to be deployable virtually everywhere. There are three compilation targets of the language that indicate the platforms on which Kotlin can run:

This is the big picture the Kotlin team is aiming for. Work needs to be done in all of these branches, especially Kotlin/Native. Still, Kotlin is a stable language that already offers many benefits over languages like Java, JavaScript, or C.32 This book focuses on its benefits for Android app development.

32. C Programming Language, http://www.bell-labs.com/usr/dmr/www/chist.html

Summary

Being a statically typed language with object-oriented as well as functional language elements, Kotlin is similar to Java 8 in many regards. However, additional language features allow the avoidance of lots of boilerplate code, thus increasing conciseness and readability. Kotlin is not an academic project and does not try to invent anything new, but instead combines what is known to work well to solve real problems in large-scale software development.

Kotlin runs on the JVM and can be used anywhere Java is used today without losing performance or increasing the runtime significantly. Its tool support and focused libraries, such as the Anko library for Android, facilitate many development tasks. Java and Android developers can typically get up to speed with Kotlin quickly and then use all mentioned features that go beyond Java 8, 9, 10, or even 11.