Kotlin from the Ground Up (Part 1)

Mike Warner
9 min readJan 17, 2020

--

The goal:

This series is aimed at developers with little to no Java/JVM experience who are having trouble grasping the language, tooling, ecosystem, and/or the “magic” in some of the web frameworks.

There are plenty of Kotlin tutorials and books out there, but they seem to be primarily aimed at people with previous Java experience.

Let’s take a straight-forward task we could do in a few lines in Python, such as “how can I turn my Hue lights on”, and go from a quick implementation in Kotlin, all the way to a web API, passing through the main components of the language, ecosystem, project structuring, and debugging in the process.

It is intended as a practical guide, so I encourage you to run the code examples in your IDE, and mess around with the code to get a “feeling” for the language.

We’ll be covering the language and tooling from the perspective of a backend developer, but a lot of these concepts apply for Kotlin native, mobile, web & multi-platform development as well.

I’ll be making comparisons with interpreted languages such as PHP, Python and JS (Node), so this tutorial assumes you have basic knowledge of any of those languages.

What will we cover in the series?

  1. Part 1: Why learn Kotlin and setting up the basics
  2. Part 2: Writing simple Kotlin programs & working with IntelliJ
  3. Part 3: What does Kotlin have to do with Java?
  4. Part 4: Adding Gradle to your project (let’s start our program!)
  5. Part 5: Diving into the Kotlin language

What does this part cover:

  1. Why learn Kotlin
  2. Setup & pre-requisites
  3. Other learning resources
  4. A few key takeaways

Why learn Kotlin

Let me start off by saying this: Kotlin is not a replacement for interpreted languages such as Python, PHP or Node.

If I need to quickly load in a CSV file, do a few data transformations, and output some JSON, I’ll probably still use Python. If I need to write a script that runs on shared hosting to perform a calculation and return a result, I’ll probably still use PHP. If I need to write a lambda to process a file and store it on S3 I’ll probably still use NodeJS.

When would I use Kotlin? When I need to write a fast, readable, null-safe, strongly-typed, scalable, multi-threaded (without all the complexity) API.

Kotlin reduces programmer mistakes, optimising for speed & scalability, whilst remaining pragmatic and easy to understand/maintain.

As a bonus you get great things out-of-the box such as:

  • Language extensibility (Add methods to standard/custom objects, e.g. make String more powerful)
  • Coroutines (async without the table flipping)
  • Compiler plugins (extend Kotlin’s capabilities further at compile time, e.g. the “all-open” plugin)
  • The Java ecosystem (where you can benefit from tons of existing libraries & resources)
  • Many more reasons (KotlinJS, Multi-platform, Native, etc.) but this tutorial focuses on the basics

My experience:

When I first started writing Kotlin I dived straight in, expecting it to be a 1:1 translation with other languages; I had mostly been using interpreter-based languages until that moment, aside from a few years in the .NET ecosystem.

How difficult could it be after all? Another day, another language.

After going through a few guides, the syntax seemed pretty enjoyable to read. However, the terminology, plugins, and tooling baffled me for months; a lot of the Kotlin tutorials out there assume you have prior Java/Android background and skip certain things.

The first day I started using Kotlin I was flung into the ecosystem, writing code using the VertX framework, JOOQ and Hikari, copy-and-pasting coroutine examples, adding Gradle dependencies (and failing consistently), completely confused by terms like “Groovy”, “Spek”, “Kotlin DSL”, “log4j”, “Classpath”, “Spring Boot”, “Maven”, “Scope functions”, etc.

Using an example repo as a starting point you can “get by” copy & pasting code around. Whenever you need to test something you can quickly do it in a scratch file, and you can check out a cheat sheet. But this doesn’t cement the language and ecosystem in your brain.

In my case I’ve always preferred a bottom-up approach, learning the purpose of each tool, how it works and how it plugs into the ecosystem, as opposed to the alternative “learning as you go” approach.

Tip #1: Start new projects often:

If you are just starting your Kotlin journey my primary tip would be: Get comfortable starting new projects. Write 10 or more projects in a few days. Don’t be afraid of pressing File → New → Project in the IDE, write small things with a single purpose, then see if you can improve the code with new that Kotlin allows you to do which you couldn’t do in your language of choice before.

Start without Gradle and work your way up.

Even though Kotlin has a much simpler learning curve than Scala (for example), there is still a lot to learn: From Coroutines to generics, Gradle to the Kotlin DSL, annotations, code generation based on API specs, DAL/entity generation based on existing schemas, etc.

One of the best ways to cement a language in your head is to frequently start new projects from the ground up.

To develop this deeply engrained knowledge it is useful to become comfortable with thinking of an idea you would usually solve with a scripting language, but instead of loading up vim or VSCode, start up IntelliJ, create a new project, and start writing code.

Why not Scala?

Wasn’t Scala the rage in startups a few years ago? What does Kotlin bring to the table? Won’t Kotlin go the same way in a few years?

Scala was designed to address many of Java’s shortcomings, it is also primarily used for functional programming, but also supports object-oriented programming. Coming from the research community (created by the Programming Methods Laboratory of École Polytechnique Fédérale de Lausanne), the preferred style of programming in the Scala community is functional.

Due to the concise & functional nature of the language, the syntax is slightly harder to grasp for people coming from an OO background. In other words, it has an academic “feel” to it.

Kotlin addresses this by taking the benefits that Scala introduced into the JVM ecosystem while adopting a simpler syntax, and introducing new tooling and language enhancements.

Why not Java?

This talk by Jake Wharton at KotlinConf 2019 compares many of the new things in Java versus the Kotlin implementations.

His point is: If Java has been progressing so much lately, and has so many things in the roadmap for the next 3-5 years to bring Java up to the same level as Kotlin (or beyond), is Kotlin as a replacement for Java even necessary?

The talk was long and quite technical (which may interest you if you wish to dive into how Kotlin code gets transpiled to Java bytecode, as well as comparisons with the Java equivalents).

The outcome of the talk was: Java is progressing, but by the time Java 19 is out, Kotlin will have also progressed further than it is today, so in short: Kotlin will still be around for a long time.

Setup & Pre-requisites

Install the Java JDK (required by Kotlin):

You need JDK 1.6+, nowadays Java changed their version numbers, so you might find yourself using JDK version 11 or 12. This matters as some Kotlin frameworks and tooling might require specific versions of the JDK, but you can have multiple installations at the same time so this won’t be an issue.

Installing the JDK might be a bit cumbersome, some versions are hard to find.

Start by looking at this page, but if you don’t find the version you are after you’ll need to search for it.

We are using Java 12 in this tutorial, which is not on that page as it is not an LTS release.

The best tutorial I’ve found on how to install Java/JDK, and how to have multiple versions and switch between them is the top answer from this StackOverflow post.

I ended up doing: brew cask install homebrew/cask-versions/adoptopenjdk12

You might be wondering at this point “what is the difference between OpenJDK and Oracle JDK?”

The short answer derived from this StackOverflow post is:

OpenJDK is an open source implementation of the Java Standard Edition platform with contribution from Oracle and the open Java community. There is no major technical difference between Oracle JDK and OpenJDK. Apart from the base code, Oracle JDK includes Oracle’s implementation of Java Plugin and Java WebStart.

Both OpenJDK and Oracle JDK are created and maintained currently by Oracle. There are quite a few versions out there and some offer LTS / security patches, some don’t… This is subject to change so I won’t be updating the benefits of each variant, it is best if you do your own research before choosing a JDK / Java version.

As of 2020 Kotlin still compiles down to Java 8 bytecode which means you will not gain language advantages by using a modern Java, only JVM advantages (such as better garbage collection, speed improvements, etc.)

Install Gradle:

Gradle is a build tool for the Java ecosystem to build and manage dependencies, it can also perform tasks which can automate actions like updating docs, generating OpenAPI/Swagger, updating DB/DAL, etc.

We’ll use it until part 2, but it’s nice to install all dependencies from the start.

  • Mac: brew install gradle
  • SDKMAN!: sdk install gradle 6.0.1
  • Other: Read this guide

Install Kotlin (from the official docs):

  • Mac: brew update && brew install kotlin
  • *Nix: curl -s [<https://get.sdkman.io>](<https://get.sdkman.io/>) | bash && sdk install kotlin
  • Ubuntu: sudo snap install --classic kotlin

What does it install?

kotlin

This is a script used to run binaries produced by the Kotlin compiler

The contents of this script is:

export KOTLIN_RUNNER=1DIR="${BASH_SOURCE[0]%/*}"
: ${DIR:="."}
"${DIR}"/kotlinc "$@"

You run it like this: kotlin -classpath hello.jar HelloKt

If you run kotlin directly it does not drop you in an interactive prompt, it expects a file as entry point

kotlinc

This is the Kotlin compiler, which you can use to produce jar files which you can then run using kotlin (or Java directly if the Kotlin runtime has been included in the JAR)

Your IDE might use kotlinc to produce the binaries it will later run

In practice you will rarely use it directly if you end up using gradle as a build tool, but it is good to get familiar with it when starting out with Kotlin.

If you run kotlinc without any parameters you will be dropped into an interactive prompt, similar to what happens when you type php -A or python in your terminal.

You can also use kotlinc to run Kotlin Scripts which we will touch upon later on.

There are two main ways of running kotlinc:

  • kotlinc hello.kt -include-runtime -d hello.jar ← This will include the Kotlin runtime so that anyone with Java can execute your program by running java -jar hello.jar
  • kotlinc hello.kt -d hello.jar ← This will compile a library, which means you need to have kotlin installed to run it. You can run it like this: kotlin -classpath hello.jar HelloKt

You can read more about kotlinc and its arguments here.

Install IntelliJ

This is not required, you can use another IDE as well (many have support for Kotlin), or even use vim/vi/emacs, however it is worth mentioning that Kotlin is spearheaded by JetBrains, makers of IntelliJ, thus it has better or more integrated support for many of Kotlin's features. That, and "scratch" files are awesome ;)

Grab the community edition of IntelliJ here.

You will need a couple of plugins to supercharge your Kotlin experience in IntelliJ which you can install by going to Preferences → Plugins:

  • Kotlin
  • Spek
  • Spek Framework

We’ll start from the command line and then introduce IntelliJ, as it makes sense to get used to kotlin/kotlinc first.

Other learning resources / methods

The official reference is great: If you would like to go deeper into any of the topics mentioned in this tutorial, check out the official reference docs, which are clear and well-structured.

This cheat sheet is also really useful to have lying around.

Kotlin from Scratch by Chike Mgbemena is a great tutorial, but focuses more on the language and concepts, whereas in this tutorial I focus more on how to compile/run the code starting from the CLI and compiler all the way up to using a build tool, writing web APIs, and deploying Kotlin projects.

This website lists a few alternative ways to get started, including guides for people who are getting started with Kotlin as their first language.

The Kotlin Koans are a great alternative if you’d like to dive straight into a hands-on approach.

A few key takeaways

  1. kotlinc: compiles Kotlin source code to Java bytecode in JARs
    It also opens an interactive prompt if run without arguments
  2. javac: compiles Java source code to Java bytecode
  3. kotlin: Script that runs a compiled Kotlin project
  4. intelliJ: IDE that improves your workflow when dealing with Kotlin

Thanks for reading, click here to go to the next part.

--

--

Mike Warner

Software Engineer specialised in PHP, Python, NodeJS, Kotlin and React