Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Kotlin Quick Start Guide
Kotlin Quick Start Guide

Kotlin Quick Start Guide: Core features to get you ready for developing applications

Arrow left icon
Profile Icon Marko Devcic
Arrow right icon
$17.99 $25.99
eBook Aug 2018 178 pages 1st Edition
eBook
$17.99 $25.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Marko Devcic
Arrow right icon
$17.99 $25.99
eBook Aug 2018 178 pages 1st Edition
eBook
$17.99 $25.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$17.99 $25.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Kotlin Quick Start Guide

Introducing Kotlin

Kotlin is a relatively new programming language, developed by JetBrains, the company that stands behind some of the most popular developer IDEs and tools, such as IntelliJ IDEA and ReSharper. JetBrains didn't create Kotlin so that they could make money on it; instead, they started the project because they wanted to solve their own development problems. In 2010, when the project started, Java was the dominant language in their code base. However, the development team wasn't happy with Java and some of its old-fashioned features. They looked for more modern alternatives to Java, but couldn't find one that satisfied their requirements in the existing JVM languages. Scala was popular at the time and was considered, but it had issues such as slow compile times.

So, they decided to create a completely new language by themselves. Since they already had a huge code base written in Java, rewriting everything in this new language wouldn't have been practical. So, Java interoperability was one of the top priorities.

Preview of the language was released in 2011 and the developer community reacted positively to it. Since then, the popularity of the language has grown rapidly. The language is open source and JetBrains' developers are not the only ones working on it. The project (language, compiler, standard library, tools, and so on) is hosted on GitHub and developers all around the world are contributing to it. Currently, there around 200 contributors to the Kotlin repository. Developers are also adopting it and more and more companies are using it in their production code. Even big companies, such as Atlassian, Square, Uber, and Pinterest, use Kotlin in production. Google also supports Kotlin development. It made Kotlin an officially supported language for building Android apps.

Now that we know how Kotlin started – and that its main goals are great Java interoperability and, at the same time, better productivity than Java – we can say that Kotlin is a general purpose, statically typed, object-oriented and functional programming language, that (primarily) targets JVM. The name Kotlin comes from an island near St.Petersburg, just as Java was named after an island in Indonesia.

In this chapter we will focus on:

  • Compiling and running Kotlin
  • Kotlin's uses
  • Java interoperability
  • Build tools
  • Setting up the development environment

Compiling and running Kotlin

Kotlin started as a JVM language, so the first compiler for Kotlin was targeting Java bytecode. But now, there are also compilers that can turn Kotlin into JavaScript and one that is still experimental, that produces native code.

Thanks to this compiler and the native code output, soon it will be possible to write apps with Kotlin that don't require additional runtimes.

This book will focus on Kotlin running on JVM, as this is the most popular usage of Kotlin today. But most of the things learned here can also be applied to other Kotlin platforms (both JavaScript and Native).

Kotlin source code is stored in files with a .kt extension, similar to the way that Java's are stored with a .java extension. Compiling Kotlin .kt files produces .class files that contain Java bytecode.

These are the same .class files that a Java compiler produces.

From there, .class files are bundled inside .jar files to form a module (a library or an app).

Since JVM only knows about Java bytecode, running apps written in Kotlin is no different from how they are written in Java.

One additional step is needed to run Kotlin modules or apps. Kotlin has its own standard library, which builds upon Java's Standard Library, and it has to be distributed with your module or app. Luckily, the Kotlin compiler does this step for us (if you are using the compiler from the command-line, just add the -include-runtime argument to a kotlinc command). Also, with the size of around 800 KB, we can say that the Kotlin standard library is relatively small and you shouldn't be worried about it.

The following diagram shows how Kotlin source code is compiled and run on the JVM:

Kotlin's uses

Now that we know that Kotlin apps run on the JVM, we also know that it basically means that Kotlin can be used for anything that Java could be used for.

Today, Java is really popular for backend (server) development and Kotlin can be used for any kind of server development. Whether it is web apps that serve HTML content, a backend for REST APIs or Microservices, Kotlin can do the job. Not only that, thanks to the Kotlin JavaScript compiler, it can also be used for building frontend web Apps. So it is entirely possible to create a web App (both backend and frontend) using only one language.

Another area where Java used to be dominant was in native Android development (other JVM languages could also be used, but none has really gained popularity on Android). This is where Kotlin has probably gained the most popularity. In one part, due to Google officially supporting it for Android development, and, secondly, because Android is still stuck on Java 6. Kotlin, with its modern features, spread rapidly among the Android developers' community.

Kotlin can also be used for developing desktop apps since both JavaFX and Swing UI libraries can be called from Kotlin.

Java interoperability

As mentioned before, Java interoperability was one of the main goals during the development of Kotlin and it is implemented seamlessly. You can call from Kotlin existing libraries compiled with Java; you can also extend a class written in Java or implement an interface written in Java and use all its types from the Java Standard Library.

But the best part is that you can have Kotlin side-by-side with the existing Java code. There's nothing preventing you from writing half of your project in Java and the other half in Kotlin.

IDEs (IntelliJ or Eclipse with a Kotlin plugin) support navigating in both Kotlin and Java files in the same project. Also, debugging and stepping through code from a project with both languages is not a problem at all. Refactoring Kotlin or Java code will also correctly update the references in another language as well.

This interoperability is also visible in the Kotlin Standard Library. Standard Library relies heavily on Java Standard Library and extends a lot of types from it. For example, Kotlin doesn't have it's own collections classes, it uses ones from Java. Java library has been battle tested and so it wouldn't make sense to reinvent the wheel.

Java-Kotlin interoperability also works in another direction. You can call functions written in Kotlin from Java, extend types and implement interfaces declared in Kotlin.

Build tools

For anything more than a simple app, you will probably use some kind of build automation tools like Maven, Ant or Gradle. The good news is that Kotlin is supported by all three of them.

In this section, will see how to set up Maven and Gradle tools for development with Kotlin.

If you are starting a new project with Gradle or Maven, your IDE probably can generate the required files for you. Here you will learn how to add Kotlin manually because you might have an existing Java project and want to start using Kotlin with it or in case you don't want to use an IDE.

Gradle

In your Gradle project, you have the build.gradle file located somewhere in the root of your project. Make sure that you have this buildScript section in that file.

buildscript {
ext.kotlin_version = '1.2.40'

repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

This tells Gradle to use a Kotlin plugin and adds Maven central to the list of repositories. With the plugin added, we still need the Kotlin standard library to be able to compile a Kotlin source code. If you have multiple Gradle modules, make sure that the module's build.gradle file in which you plan to use Kotlin has the following:

apply plugin: "kotlin"

repositories {
mavenCentral()
}

dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}

If you don't have multiple build.gradle files, then put this to the root build.gradle file. The same one in which you added the Kotlin plugin.

You can also set various compiler options under the compile Kotlin section. For example, with the kotlinOptions.jvmTarget = "1.8" option we told the Kotlin compiler to produce Java 1.8 compatible bytecode.

Now, if you sync your Gradle project, you should be able to add Kotlin files to it and compile them with Gradle.

Maven

If Maven is your build tool of choice, then setting up Kotlin will be just as easy.

In the same way as with Gradle, we first need to add a Kotlin plugin to a pom.xml file. You can do this by adding these lines to the plugins section:

<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals><goal>compile</goal></goals>
</execution>
</executions>
</plugin>

We can define a Kotlin version at one place, inside the properties section:

<properties>
<kotlin.version>1.2.40</kotlin.version>
</properties>

In the same way as with Gradle, the Kotlin standard library needs to be added to dependencies.

<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>

If you are targeting JDK 8, you can replace kotlin-stdlib with kotlin-stdlib-jdk8 so you can have Kotlin extension functions that cover the latest APIs from JDK 8.

This should be enough if you plan on only writing Kotlin. If you are mixing Kotlin and Java inside a Maven project, a Kotlin compiler needs to run before a Java compiler. To instruct Maven to compile Kotlin first, the Kotlin plugin needs to be before the Maven compiler plugin.

Here's what the complete build section looks like:

<build>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals> <goal>compile</goal> </goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/src/main/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<executions>
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals> <goal>compile</goal> </goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

Finally, there are various Kotlin compiler options that can be set under the configuration section of a Kotlin plugin. Here's an example of how to instruct the compiler to produce a Java 1.8 compatible bytecode.

<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<jvmTarget>1.8</jvmTarget>
</configuration>
</plugin>

Setting up the development environment

Although you could use a basic text editor for writing Kotlin source code and compile it using the command-line tools, you will make your life easier if you use an IDE for coding. IDE can provide code completion, syntax highlighting, stepping through code while debugging, refactoring, and more.

IntelliJ IDEA is probably the most popular IDE for Java today. The IDE comes from the same company that created Kotlin and, of course, Kotlin is a first class citizen inside IntelliJ. This book uses IntelliJ, and it is recommended that you use it as well. But other popular IDEs for Java could also work, such as Eclipse or NetBeans (a Kotlin plugin would be needed). The great thing about IntelliJ is that the latest versions already come with a Kotlin plugin pre-installed, so the IDE is ready for Kotin development out of the box. This plugin already has a Kotlin compiler and also enables Kotlin syntax highlighting inside the code editor.

Another benefit of using IntelliJ is that it comes with a Java to Kotlin converter. If you have some Java code, or you are working in a mixed (both Java and Kotlin) project, you can convert Java code to Kotlin with the click of a button. Some minor changes might be needed in the resulting Kotlin code but in general, this converter works reasonably well.

IntelliJ has a paid for Ultimate version and a free Community version. The Express version has everything needed for Kotlin development and can be downloaded from the JetBrains website https://www.jetbrains.com/idea/download/. It's available for all platforms (Mac, Linux, and Windows).

Finally, if you are just trying out the syntax or just getting a feel for the language, there is a free online compiler and IDE available at https://try.kotlinlang.org/.

What's great about this online IDE is that it has plenty of examples of Kotlin features. There is also a section called Koans which has smaller code problems with the goal of teaching Kotlin. So, it might be worth checking it out.

Now that we have an IDE installed, let's get the first taste of Kotlin. Inside Intellij, start a new project and select Kotlin from the bar on the left and then select the Kotlin/JVM option, as seen in the following screenshot:

On the next screen, enter your project name and select KotlinJavaRuntime in the Use library section.

This will be enough to compile and run Kotlin code from the IDE. For smaller examples, setting up Maven or Gradle would be an overkill. 

Now that we have a Kotlin project, let's add some Kotlin code: the standard Hello World printed to the console. Add a file named Main.kt inside the src folder.

Inside that file add the following code:

fun main(args: Array<String>) {
println("Hello World!")
}

Now, there should be a little green icon in the gutter of the text editor and if you click it you should see "Hello World!" in the output.

Summary

In this chapter, we took a look at the history of Kotlin and explained how it compiles to Java bytecode. Thanks to Kotlin's great interoperability with Java, we've seen that it has wide use cases, from Backend apps to Mobile and Desktop apps. We'll be using IntelliJ IDEA as our IDE in this book, as Kotlin is supported out of the box. Finally, we discussed build tools that support Kotlin.

In the next chapter, we'll start with exploring the language and learning the basics.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Start programming with Kotlin
  • Explore Kotlin language syntax, standard libraries and Java Interoperability
  • Builds an example application with what you learn

Description

Kotlin is a general purpose, object-oriented language that primarily targets the JVM and Android. Intended as a better alternative to Java, its main goals are high interoperability with Java and increased developer productivity. Kotlin is still a new language and this book will help you to learn the core Kotlin features and get you ready for developing applications with Kotlin. This book covers Kotlin features in detail and explains them with practical code examples.You will learn how to set up the environment and take your frst steps with Kotlin and its syntax. We will cover the basics of the language, including functions, variables, and basic data types. With the basics covered, the next chapters show how functions are first-class citizens in Kotlin and deal with the object-oriented side of Kotlin. You will move on to more advanced features of Kotlin. You will explore Kotlin's Standard Library and learn how to work with the Collections API. The book finishes by putting Kotlin in to practice, showing how to build a desktop app. By the end of this book, you will be confident enough to use Kotlin for your next project.

Who is this book for?

This book is intended for anybody who wants to learn the most important Kotlin features. No experience of Kotlin is expected.

What you will learn

  • • Programming in Kotlin language syntax, basic types, control ?ow, classes, and OOP
  • • Writing functions and functional programming in Kotlin
  • • Defning and importing from packages in Kotlin
  • • Running Kotlin on JVMs and Android runtimes
  • • Working with the Kotlin Standard Library and advanced features of Kotlin programming
  • • Setting up a Kotlin development environment with JetBrains tools
  • • Building real-world applications with Kotlin

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 31, 2018
Length: 178 pages
Edition : 1st
Language : English
ISBN-13 : 9781789342598
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 31, 2018
Length: 178 pages
Edition : 1st
Language : English
ISBN-13 : 9781789342598
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 131.97
Kotlin Quick Start Guide
$32.99
Kotlin Standard Library Cookbook
$43.99
Kotlin Programming Cookbook
$54.99
Total $ 131.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Introducing Kotlin Chevron down icon Chevron up icon
Kotlin Basics Chevron down icon Chevron up icon
Classes and Object-Oriented Programming Chevron down icon Chevron up icon
Functions and Lambdas Chevron down icon Chevron up icon
Advanced Kotlin Chevron down icon Chevron up icon
Kotlin Standard Library Chevron down icon Chevron up icon
Coding a Dictionary App with Kotlin Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.