Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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 Stephen Samuel Profile Icon Stefan Bocutiu
Arrow right icon
R$49.99 R$173.99
eBook May 2019 514 pages 2nd Edition
eBook
R$49.99 R$173.99
Paperback
R$217.99
Subscription
Free Trial
Renews at R$50p/m
Arrow left icon
Profile Icon Stephen Samuel Profile Icon Stefan Bocutiu
Arrow right icon
R$49.99 R$173.99
eBook May 2019 514 pages 2nd Edition
eBook
R$49.99 R$173.99
Paperback
R$217.99
Subscription
Free Trial
Renews at R$50p/m
eBook
R$49.99 R$173.99
Paperback
R$217.99
Subscription
Free Trial
Renews at R$50p/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
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781789808742
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
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
R$50 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
R$500 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 R$25 each
Feature tick icon Exclusive print discounts
R$800 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 R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 681.97
Learn Kotlin Programming
R$217.99
Android Programming with Kotlin for Beginners
R$217.99
Mastering Kotlin
R$245.99
Total R$ 681.97 Stars icon
Banner background image

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

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.