Kotlin tutorial: Get started with Kotlin

Kotlin can provide huge benefits to developers currently working on Java and Android projects. Here’s how

Kotlin tutorial: Get started with Kotlin
Thinkstock

As I discussed in my article “What is Kotlin? The Java alternative explained,” Kotlin is a general purpose, open source, statically typed “pragmatic” programming language that combines object-oriented and functional programming features. You can use Kotlin to build applications for the Java Virtual Machine (JVM), Android, browsers, and native apps on MacOS, Linux, Windows, iOS, WebAssembly, and Android. Kotlin was created by JetBrains and released to open source under the Apache 2 license.

Why learn Kotlin? The short answer is that Kotlin is a better language for the JVM than Java. Kotlin is less verbose, supports all the features of functional programming, eliminates the danger of null pointer references, streamlines the handling of null values, and maintains 100 percent interoperability with Java and Android. All of that will make you a more productive programmer than you would be writing Java, even if you start by using Kotlin to build new features into an existing Java application.

Try Kotlin online

You can try Kotlin online without installing anything on your computer. On the try.kotlinlang.org site (shown below) you might start by reading through and trying the examples, working through the Kotlin Koans, and then, if you want additional reinforcement, trying all the Kotlin in Action examples. Both the Problems section and the Koans provide unit tests and ask you to code answers that satisfy all of the tests. The knowledge needed to complete the Problems section is covered in previous sections; the Koans contain links to the appropriate Kotlin documentation in addition to a problem statement and a code skeleton.

For extra credit, join Advent of Code and use the appropriate section of the Try Kotlin site to code your answers. You can log into both the Kotlin and Advent of Code sites with your existing social media credentials.

try kotlin IDG

Try Kotlin online at try.kotlinlang.org

Install Kotlin on your machine

In addition to the online option, which is more useful for learning than for serious coding, the official Kotlin language site offers four local options for developing with Kotlin, as shown below. IntelliJ IDEA Community Edition (free) and Ultimate (subscription) both ship with the Kotlin plug-in. Android Studio, a free subset of IntelliJ IDEA that is specialized to Android development, has shipped with the Kotlin plug-in installed since version 3.0. You can install the plug-in into an older version if necessary.

You can add a Kotlin plug-in to Eclipse (free), if that’s your standard Java IDE. I don’t recommend Eclipse for novices, as it can be hard to learn. At the same time, I don’t recommend that an experienced and happy Eclipse user switch to a different IDE.

The command-line compiler, kotlinc, can be installed a number of different ways, depending on your system. You don’t need to install it if you are using IntelliJ IDEA, Android Studio, or Eclipse with the Kotlin plug-in. You do need to install it if you want to use a different editor or integrate with command-line Java build tools such as Gradle, Maven, or Ant. Once you have the Kotlin compiler installed, you can use it to build Java-compatible JAR files, either for use as library files or as runnable applications. You can also use the Kotlin compiler as a REPL interactive shell.

There are also useful Kotlin plug-ins for other popular editors including Visual Studio Code and Sublime Text. These plug-ins supply syntax highlighting at a minimum. There’s also a Kotlin code completion (IntelliSense) plug-in for Visual Studio Code.

kotlin ides IDG

Work with Kotlin locally using IntelliJ IDEA, Android Studio, Eclipse, or the command-line compiler. 

Kotlin Hello World

You can find a getting started tutorial on the official Kotlin site for IntelliJ IDEA, Eclipse, and the command-line compiler. In the screenshots below, I offer a slightly more complete tutorial for Kotlin using IntelliJ IDEA. I used the Ultimate edition; if you use the free Community edition, there are a couple of places where you will have to use a command line or another program to accomplish the same goals.

kotlin intellij idea IDG

Create a Kotlin/JVM project. 

Start by opening IntelliJ IDEA and creating a new project. In the official tutorial they show starting with the Java category and then picking Kotlin; for simplicity I instead suggest that you start with the Kotlin category and pick Kotlin/JVM. You may want to try the Kotlin/JS and Kotlin Multiplatform projects later, with the same code.

kotlin new project IDG

Name your new Kotlin project HelloWorld and accept the Java version and runtime defaults. 

I called the project HelloWorld and located it on the external drive where I keep my Git repositories. I accepted the default choices for the Java version and the Kotlin runtime.

kotlin new kotlin file IDG

Add a new Kotlin file to the src folder. 

Add a new Kotlin file in the src folder, using the context menu.

kotlin main IDG

Type in your Kotlin code. 

Add the code shown above. There’s a shortcut to generate the main function skeleton: type “main” followed by <tab>. You’ll discover a few helpful completions as you type the function body, println(“Hello, World!”). Note that, unlike Java, Kotlin statements do not need to end in a semicolon if they are followed by a <newline>.

kotlin build IDG

Build your Kotlin app. 

Go ahead and build the HelloWorld project, using the Build menu. If there are errors, fix them and build the project again.

kotlin run helloworldkt IDG

Run the application. 

Run HelloWorldKt using the context menu or the Run menu.

kotlin run helloworldkt result IDG

Examine the output. 

There might be warnings, such as the one shown above, but the output should be “Hello, World!” just as expected, and the exit code should be 0.

kotlin create git repo IDG

Create a version control repo for the project. 

Now that you know the program works, create a repository for it. I did this locally using Git, from within IntelliJ IDEA.

kotlin add to vcs IDG

Add the project to your new repo. 

I added all the files in the project to Git from a context menu, after selecting them from the Unversioned Files window.

kotlin commit changes IDG

Commit the changes to the repo. 

Then I committed my changes to my local Git repository, after creating a descriptive commit message. While this particular commit message may seem superfluous, you will find that accurate, descriptive commit messages make understanding a code repository much easier.

kotlin helloworldkt debug IDG

Set a breakpoint to debug your Kotlin app. 

Here I have set a breakpoint on line 2 and debugged HelloWorldKt. If there were more variables defined at this point they would show up in the debugger.

Convert Java to Kotlin

All of the IntelliJ-based IDEs allow you to convert existing Java to Kotlin easily. In the online environment, you copy the Java, bring up a Convert from Java window, paste your code, and press the button to convert to Kotlin. Then select and copy the generated Kotlin code, close the window, and paste the Kotlin code to the destination.

IntelliJ IDEA and Android studio eliminate the intermediate step of using the pop-up window. Just copy the Java and paste it into a Kotlin file, and the IDE will convert it automatically.

Kotlin Koans and the EduTools plug-in

The Kotlin Koans are a series of coding exercises for learning Kotlin syntax. There are three ways to play with them: online, in your IDE using the EduTools plug-in, and in your IDE or editor after cloning their GitHub repository.

It’s worth completing all 42 Koans. It’s also worth installing EduTools so that you can go through other courses, either from Stepik or from other sources.

The Koans, and all EduTools courses, combine a problem definition and code skeleton with unit tests and ask you to code answers that satisfy all the tests. You can author your own courses with EduTools at a later time if you wish. Among other things, it’s good practice for writing unit tests. For now, you are a Learner.

kotlin edutools IDG

Install the EduTools plug-in to take advantage of Kotlin courses. 

Once EduTools has been installed and you have rebooted your IDE, you can open courses by choosing File > Browse Courses.

kotlin edutools kotlin koans IDG

Learn Kotlin syntax by completing the Kotlin Koans. 

Kotlin for the server JVM

One of the most prevalent uses of Java is for application and web servers. Kotlin fits beautifully into those scenarios, not least because it allows for incremental migration with full interoperability on the JVM. You really don’t want to mess with a million lines of working Java code without a good reason, so it’s important that you can add new Kotlin modules to a Java application without needing to change any existing code.

In addition to interoperability and incremental migration, Kotlin offers improved scalability over Java code by using coroutines for asynchronous operations. At its core, suspending a coroutine has much less overhead than blocking a thread, since the mechanism to suspend and continue a coroutine is implemented at the compiler level as a state machine, with no context switch or any other need for intervention by the operating system.

Several prominent frameworks now use Kotlin. One is Spring, which as of version 5 uses Kotlin to provide null safety for the entire framework and offers extensions to dramatically simplify some of the APIs when called from Kotlin.

There are a couple of 100 percent Kotlin server apps currently in production. One of them is JetBrains’ own account app, which handles the license sales and validation process, and has run since 2015. Another is Corda, an open-source distributed ledger supported by major banks.

Kotlin for JavaScript

The second possible compilation target (or transpilation target, to be accurate) for Kotlin is JavaScript. You can use the generated JavaScript in a webpage to manipulate the DOM and interact with web graphics, for example WebGL. You can also use the transpiled JavaScript in a Node.js app on a server or desktop.

There is special support for Kotlin and React including the Kotlin React bindings and the Create React Kotlin App. For strong typing, you can convert TypeScript definitions from the Definitely Typed type definitions repository to Kotlin using the ts2kt tool. For weak typing, use the dynamic type.

Kotlin for Android

Google and JetBrains officially support Kotlin in Android Studio and IntelliJ IDEA, and several major Android apps are now written either entirely (Basecamp) or partially (Pinterest) in Kotlin. Pinterest reports that it completely eliminated null pointer exceptions (NPEs) after adopting Kotlin. Another major app, Keepsafe, was originally written in Java, then converted entirely to Kotlin, leading to a 30 percent decrease in source line count and a 10 percent decrease in method count.

In order to develop Android Dalvik Virtual Machine (DVM) apps in Kotlin you basically need to install one of the two IDEs I mentioned, plus the Android SDK. To try out your apps, you’ll need an Android device or some Android emulators.

Kotlin for compiled native apps

Finally, you can use Kotlin in combination with the LLVM compiler to create native applications without a dependency on a virtual machine for Windows, Linux, MacOS, iOS, WebAssembly, and Android. Yes, that’s right, you can build compiled Kotlin native apps for Android in addition to building Kotlin DVM apps. Whether you’ll want to do that is another question, since Android has the DVM built-in.

According to JetBrains, “Kotlin/Native is primarily designed to allow compilation for platforms where virtual machines are not desirable or possible (such as iOS or embedded targets), or where a developer is willing to produce a reasonably-sized self-contained program without the need to ship an additional execution runtime.”

Kotlin can provide huge benefits to developers currently working on Java and Android projects, starting with the blanket elimination of null pointer exceptions, continuing to full support for functional programming, and on to allowing you to write less code than you would in Java. Kotlin also works well when compiled to native code or transpiled to JavaScript.

As far as I can tell, there are no serious drawbacks to Kotlin compared to Java. What’s holding you back?

Copyright © 2018 IDG Communications, Inc.