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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learn Kotlin Programming
Learn Kotlin Programming

Learn Kotlin Programming: A comprehensive guide to OOP, functions, concurrency, and coroutines in Kotlin 1.3 , Second Edition

Arrow left icon
Profile Icon Samuel Profile Icon Bocutiu
Arrow right icon
€18.99 per month
Paperback May 2019 514 pages 2nd Edition
eBook
€15.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Samuel Profile Icon Bocutiu
Arrow right icon
€18.99 per month
Paperback May 2019 514 pages 2nd Edition
eBook
€15.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€15.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learn Kotlin Programming

Getting Started with Kotlin

It is time to write code. In this chapter, we will go over and write the typical entry code example for every language—the famous Hello World!. In order to do this, we will need to set up the initial environment required to develop software with Kotlin. We will provide a few examples using the compiler from the command line, and then we will look at the typical way of programming using the integrated development environments (IDEs) and build tools available.

Kotlin is a Java virtual machine (JVM) language, and so the compiler will emit Java bytecode. Because of this, naturally, Kotlin code can call Java code, and vice versa! Therefore, you need to have the Java Development Kit (JDK) installed on your machine. To be able to write code for Android, where the most recent supported Java version is 6, the compiler needs to translate your code to bytecode...

Technical requirements

Throughout this book, all the code examples will run with JDK 8. If you are new to the JVM world, you can get the latest version from http://www.oracle.com/technetwork/java/javase/downloads/index.html.

In Chapter 7, Null Safety, Reflection, and Annotations, the examples will draw heavily on classes provided by the reflection API. This API is available through the kotlin-reflect.jar located on maven central at https://search.maven.org/search?q=a:kotlin-reflect.

Additionally, the code snippets used in this book can be found on GitHub at the following repository https://github.com/PacktPublishing/Programming-Kotlin.

Using the command line to compile and run Kotlin code

To write and execute code written in Kotlin, you will need its runtime and the compiler. At the time of writing, the stable release of Kotlin is 1.3.31. Every runtime release comes with its own compiler version. To get your hands on it, navigate to https://github.com/JetBrains/kotlin/releases/tag/v1.3.31, scroll to the bottom of the page, and download and unpack the ZIP archive, kotlin-compiler-1.3-31.zip, to a known location on your machine. The output folder will contain a directory called bin with all the scripts required to compile and run Kotlin on Windows, Linux, or macOS. You need to make sure the bin folder location is part of your system path in order to call kotlinc without having to specify the full path.

If your machine runs Linux or macOS, there is an even easier way to install the compiler by using sdkman. All...

Kotlin runtime

When we compiled Hello World! and produced the JAR, we instructed the compiler to bundle in the Kotlin runtime. Why is the runtime needed? Take a closer look at the following bytecode that was generated, if you haven't already done so. To be more specific, look at line 3. It invokes a method to validate the fact that the args variable is not null; therefore, if you compile the code without asking for the runtime to be bundled in, and then try to run it, you will get an exception:

$ kotlinc HelloWorld.kt -d HelloWorld.jar
$ java -jar HelloWorld.jar
Exception in thread "main" java.lang.NoClassDefFoundError:  kotlin/jvm/internal/Intrinsics at HelloWorldKt.main(HelloWorld.kt)
Caused by: java.lang.ClassNotFoundException:  kotlin.jvm.internal.Intrinsics

The runtime footprint is very small; at approximately 800 K, you can't argue otherwise. Kotlin comes...

The REPL

These days, most languages provide an interactive shell, and Kotlin is no exception. If you want to quickly write some code that you won't use again, then the REPL is a good tool to have. Some people prefer to test their methods quickly, but you should always write unit tests rather than using the REPL to validate that the output is correct.

Note: REPL is the common name when referring to an interactive shell, and is an abbreviation for read, evaluate, print, loop.

You can start the REPL by adding dependencies to the classpath in order to make them available within the instance. To look at an example, we will use the Joda library to deal with the date and time. First, we need to download the JAR. In a Terminal window, use the following commands:

$ wget https://github.com/JodaOrg/joda-time/releases/download/v2.9.4/joda-time-2.9.4-dist.tar.gz
$ tar xvf joda-time-2...

Kotlin for scripting

Kotlin can also be run as a script. If bash or Perl is not for you, now you have an alternative.

Say you want to delete all files that are older than N given days. The following code example does just that:

    import java.io.File 
    val purgeTime = System.currentTimeMillis() - args[1].toLong() * 24  * 60 * 60 * 1000 
    val folders = File(args[0]).listFiles { file -> file.isFile } 
    folders ?.filter { 
      file -> file.lastModified() < purgeTime } 
    ?.forEach { 
      file -> println("Deleting ${file.absolutePath}") 
      file.delete() 
    } 

Create a file named delete.kts with the preceding content. Note the predefined variable args, which contains all the incoming parameters passed when it is invoked. You might wonder what the ? character is doing there. If you are familiar with the C# language and you know about nullable...

Kotlin with Gradle

If you are familiar with the build tool landscape, you might be in one of three camps—Maven, Gradle, or SBT (more likely if you are a Scala developer). I am not going to go into the details, but we will present the basics of Gradle, the modern open source polyglot build automation system, and leave it up to the curious to find out more from http://gradle.org. Before we continue, please make sure you have it installed and available in your classpath in order for it to be accessible from the Terminal. If you have SDKMAN, you can install it using this command:

$ sdk install gradle 3.0

The build system comes with some baked-in templates, albeit limited ones, and, in its latest 3.0 version, Kotlin is not yet included. Hopefully, this shortfall will be dealt with sooner rather than later; however, it takes very little effort to configure support for it. First...

Kotlin with Maven

If you still prefer to stick with good old Maven, there is no problem. There is a plugin for it to support Kotlin as well. If you don't have Maven on your machine, you can follow the instructions at https://maven.apache.org/install.html to get it installed on your local machine.

Just as we did with Gradle, let's use the built-in templates to generate the project folder and file structure. From the Terminal, run the following command in an empty directory:

$ mvn archetype:generate -DgroupId=com.programming.kotlin 
-DartifactId=chapter01 -DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
maven-archetype- quickstart => maven-archetype-quickstart

This will generate the pom.xml file and the src folder for Maven. But before we add the file containing the kotlin code, we need to enable the plugin. Just as before, start by deleting App...

IntelliJ and Kotlin

Coding using Vim/nano is not everyone's first choice. Working without the help of an IDE with its code completion, IntelliSense, shortcuts for adding files, or refactoring code can prove challenging depending on how complex the project is.

For a while now, in the JVM world, people's first choice when it comes to their integrated development environment has been IntelliJ. The tool is made by the same company that created Kotlin—JetBrains. Given the integration between the two of them, it would be my first choice of IDE to use, but, as we will see in the next section, it is not the only option.

IntelliJ comes in two versions—Ultimate and Community (free). For the code we will be using over the course of this book, the free version is sufficient. If you don't already have it installed, you can download it from https://www.jetbrains...

Eclipse and Kotlin

There might be some of you who still prefer Eclipse IDE to IntelliJ; don't worry, you can still develop Kotlin code without having to move away from it. At this point, I assume you already have the tool installed. From the menu, navigate to Help | Eclipse Marketplace, look for the Kotlin plugin, and install it (I am working with the latest distribution—Eclipse Neon).

Once you have installed the plugin and restarted the IDE, you are ready to create your first Kotlin project. From the menu, select File | New | Project, and you should see the following dialog:

New Kotlin project

Click the Next button to move to the next step, and once you have chosen the source code location, click the Finish button. This is not a Gradle or Maven project! You can choose one of the two, but then you will have to manually modify the build.gradle or pom.xml file, as we...

Mixing Kotlin and Java in a project

Using different languages within the same project is quite common; I have encountered projects where a mix of Java and Scala files formed the code base. Could we do the same with Kotlin? Absolutely. Let's work on the project we created earlier in the Kotlin with Gradle section. You should see the following directory structure in your IntelliJ (the standard template for a Java/Kotlin project):

Project layout

You can place the Java code within the java folder. Add a new package to the java folder with the same name as the one present in the kotlin folder: com.programming.kotlin.chapter01. Navigate to New | Java class named CarManufacturer.java and use the following code for the purpose of the exercise:

    public class CarManufacturer { 
      private final String name; 
      public CarManufacturer(String name) { 
        this.name =...

Summary

This chapter described how you can set up your development environment with Gradle, Maven, IntelliJ, or Eclipse. Now, you are able to run and execute the examples given in the rest of the book, as well as experiment with your own Kotlin code.

In Chapter 2, Kotlin Basics, we will delve into the basic constructs you will use on a daily basis when coding in Kotlin.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn the fundamentals of Kotlin to write high-quality code
  • Test and debug your applications with the different unit testing frameworks in Kotlin
  • Explore Kotlin's interesting features such as null safety, reflection, and annotations

Description

Kotlin is a general-purpose programming language used for developing cross-platform applications. Complete with a comprehensive introduction and projects covering the full set of Kotlin programming features, this book will take you through the fundamentals of Kotlin and get you up to speed in no time. Learn Kotlin Programming covers the installation, tools, and how to write basic programs in Kotlin. You'll learn how to implement object-oriented programming in Kotlin and easily reuse your program or parts of it. The book explains DSL construction, serialization, null safety aspects, and type parameterization to help you build robust apps. You'll learn how to destructure expressions and write your own. You'll then get to grips with building scalable apps by exploring advanced topics such as testing, concurrency, microservices, coroutines, and Kotlin DSL builders. Furthermore, you'll be introduced to the kotlinx.serialization framework, which is used to persist objects in JSON, Protobuf, and other formats. By the end of this book, you'll be well versed with all the new features in Kotlin and will be able to build robust applications skillfully.

Who is this book for?

If you’re a beginner or intermediate programmer who wants to learn Kotlin to build applications, this book is for you. You’ll also find this book useful if you’re a Java developer interested in switching to Kotlin.

What you will learn

  • Explore the latest Kotlin features in order to write structured and readable object-oriented code
  • Get to grips with using lambdas and higher-order functions
  • Write unit tests and integrate Kotlin with Java code
  • Create real-world apps in Kotlin in the microservices style
  • Use Kotlin extensions with the Java collections library
  • Uncover destructuring expressions and find out how to write your own
  • Understand how Java-nullable code can be integrated with Kotlin features

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 29, 2019
Length: 514 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789802351
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 29, 2019
Length: 514 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789802351
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 92.97
Learn Kotlin Programming
€29.99
Android Programming with Kotlin for Beginners
€29.99
Mastering Kotlin
€32.99
Total 92.97 Stars icon

Table of Contents

20 Chapters
Section 1: Fundamental Concepts in Kotlin Chevron down icon Chevron up icon
Getting Started with Kotlin Chevron down icon Chevron up icon
Kotlin Basics Chevron down icon Chevron up icon
Object-Oriented Programming in Kotlin Chevron down icon Chevron up icon
Section 2: Practical Concepts in Kotlin Chevron down icon Chevron up icon
Functions in Kotlin Chevron down icon Chevron up icon
Higher-Order Functions and Functional Programming Chevron down icon Chevron up icon
Properties Chevron down icon Chevron up icon
Null Safety, Reflection, and Annotations Chevron down icon Chevron up icon
Generics Chevron down icon Chevron up icon
Data Classes Chevron down icon Chevron up icon
Collections Chevron down icon Chevron up icon
Testing in Kotlin Chevron down icon Chevron up icon
Microservices with Kotlin Chevron down icon Chevron up icon
Section 3: Advanced Concepts in Kotlin Chevron down icon Chevron up icon
Concurrency Chevron down icon Chevron up icon
Coroutines Chevron down icon Chevron up icon
Application of Coroutines Chevron down icon Chevron up icon
Kotlin Serialization 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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.