Part 1. Introducing Kotlin
The goal of this part of the book is to get you productive writing Kotlin code that uses existing APIs. Chapter 1 will introduce you to the general traits of Kotlin. In chapters 2-4, youâll learn how the most basic Java programming conceptsâstatements, functions, classes, and typesâmap to Kotlin code, and how Kotlin enriches them to make programming more pleasant. Youâll be able to rely on your existing knowledge of Java, as well as tools such as IDE coding-assistance features and the Java-to-Kotlin converter, to get up to speed quickly. In chapter 5, youâll find out how lambdas help you effectively solve some of the most common programming tasks, such as working with collections. Finally, in chapter 6, youâll become familiar with one of the key Kotlin specialties: its support for dealing with null values.
Chapter 1. Kotlin: what and why
This chapter covers
- A basic demonstration of Kotlin
- The main traits of the Kotlin language
- Possibilities for Android and server-side development
- What distinguishes Kotlin from other languages
- Writing and running code in Kotlin
What is Kotlin all about? Itâs a new programming language targeting the Java platform. Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code. It can be used almost everywhere Java is used today: for server-side development, Android apps, and much more. Kotlin works great with all existing Java libraries and frameworks and runs with the same level of performance as Java. In this chapter, weâll explore Kotlinâs main traits in detail.
1.1. A taste of Kotlin
Letâs start with a small example to demonstrate what Kotlin looks like. This example defines a Person class, creates a collection of people, finds the oldest one, and prints the result. Even in this small piece of code, you can see many interesting features of Kotlin; weâve highlighted some of them so you can easily find them later in the book. The code is explained briefly, but please donât worry if something isnât clear right away. Weâll discuss everything in detail later.
If youâd like to try running this example, the easiest option is to use the online playground at http://try.kotl.in. Type in the example and click the Run button, and the code will be executed.
Listing 1.1. An early taste of Kotlin
You declare a simple data class with two properties: name and age. The age property is null by default (if it isnât specified). When creating the list of people, you omit Aliceâs age, so the default value null is used. Then you use the maxBy function to find the oldest person in the list. The lambda expression passed to the function takes one parameter, and you use it as the default name of that parameter. The Elvis operator (?:) returns zero if age is null. Because Aliceâs age isnât specified, the Elvis operator replaces it with zero, so Bob wins the prize for being the oldest person.
Do you like what youâve seen? Read on to learn more and become a Kotlin expert. We hope that soon youâll see such code in your own projects, not only in this book.
1.2. Kotlinâs primary traits
You probably already have an idea what kind of language Kotlin is. Letâs look at its key attributes in more detail. First, letâs see what kinds of applications you can build with Kotlin.
1.2.1. Target platforms: server-side, Android, anywhere Java runs
The primary goal of Kotlin is to provide a more concise, more productive, safer alternative to Java thatâs suitable in all contexts where Java is used today. Java is an extremely popular language, and itâs used in a broad variety of environments, from smart cards (Java Card technology) to the largest data centers run by Google, Twitter, LinkedIn, and other internet-scale companies. In most of these places, using Kotlin can help developers achieve their goals with less code and fewer annoyances along the way.
The most common areas to use Kotlin are:
- Building server-side code (typically, backends of web applications)
- Building mobile applications that run on Android devices
But Kotlin works in other contexts as well. For example, you can use the Intel Multi-OS Engine (https://software.intel.com/en-us/multi-os-engine) to run Kotlin code on iOS devices. To build desktop applications, you can use Kotlin together with TornadoFX (https://github.com/edvin/tornadofx) and JavaFX.[1]
1
âJavaFX: Getting Started with JavaFX,â Oracle, http://mng.bz/500y.
In addition to Java, Kotlin can be compiled to JavaScript, allowing you to run Kotlin code in the browser. But as of this writing, JavaScript support is still being explored and prototyped at JetBrains, so itâs out of scope for this book. Other platforms are also under consideration for future versions of the language.
As you can see, Kotlinâs target is quite broad. Kotlin doesnât focus on a single problem domain or address a single type of challenge faced by software developers today. Instead, it provides across-the-board productivity improvements for all tasks that come up during the development process. It gives you an excellent level of integration with libraries that support specific domains or programming paradigms. Letâs look next at the key qualities of Kotlin as a programming language.
1.2.2. Statically typed
Just like Java, Kotlin is a statically typed programming language. This means the type of every expression in a program is known at compile time, and the compiler can validate that the methods and fields youâre trying to access exist on the objects youâre using.
This is in contrast to dynamically typed programming languages, which are represented on the JVM by, among others, Groovy and JRuby. Those languages let you define variables and functions that can store or return data of any type and resolve the method and field references at runtime. This allows for shorter code and greater flexibility in creating data structures. But the downside is that problems like misspelled names canât be detected during compilation and can lead to runtime errors.
On the other hand, in contrast to Java, Kotlin doesnât require you to specify the type of every variable explicitly in your source code. In many cases, the type of a variable can automatically be determined from the context, allowing you to omit the type declaration. Hereâs the simplest possible example of this:
val x = 1
Youâre declaring a variable, and because itâs initialized with an integer value, Kotlin automatically determines that its type is Int. The ability of the compiler to determine types from context is called type inference.
Following are some of the benefits of static typing:
- Performanceâ Calling methods is faster because thereâs no need to figure out at runtime which method needs to be called.
- Reliabilityâ The compiler verifies the correctness of the program, so there are fewer chances for crashes at runtime.
- Maintainabilityâ Working with unfamiliar code is easier because you can see what kind of objects the code is working with.
- Tool supportâ Static typing enables reliable refactorings, precise code completion, and other IDE features.
Thanks to Kotlinâs support for type inference, most of the extra verbosity associated with static...