Learn Kotlin Programming
eBook - ePub

Learn Kotlin Programming

A comprehensive guide to OOP, functions, concurrency, and coroutines in Kotlin 1.3, 2nd Edition

Stephen Samuel, Stefan Bocutiu

Condividi libro
  1. 514 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Learn Kotlin Programming

A comprehensive guide to OOP, functions, concurrency, and coroutines in Kotlin 1.3, 2nd Edition

Stephen Samuel, Stefan Bocutiu

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Delve into the world of Kotlin and learn to build powerful Android and web applications

Key Features

  • 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

Book 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.

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

Who this book is 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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Learn Kotlin Programming è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Learn Kotlin Programming di Stephen Samuel, Stefan Bocutiu in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatica e Programmazione. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2019
ISBN
9781789808742
Edizione
2
Argomento
Informatica

Section 1: Fundamental Concepts in Kotlin

In the first section of the book, you will be introduced to Kotlin. You will learn how to set up your system to write your first Kotlin program and run it. This will include configuring a build system, such as Gradle or Maven, to handle dependencies used by your programs. Then, the core concepts of Kotlin, such as basic syntax for variables and values, expressions, and loops, will be explained, giving you the basic building blocks required to write a non-trivial program. In addition, the types available in Kotlin, and how nulls interact with them, will also be covered. Finally, you will see how the basic constructs of Kotlin can be combined to form objects, and how these objects can interact in what is known as object-oriented programming.
The following chapters will be covered in this section:
  • Chapter 1, Getting Started with Kotlin
  • Chapter 2, Kotlin Basics
  • Chapter 3, Object-Oriented Programming in Kotlin

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 that is at least compatible with Java 6.
In this chapter, you will learn how to do the following:
  • Use the command line to compile and execute code written in Kotlin
  • Use the REPL and write Kotlin scripts
  • Create a Gradle project with Kotlin enabled
  • Create a Maven project with Kotlin enabled
  • Use IntelliJ to create a Kotlin project
  • Use Eclipse IDE to create a Kotlin project
  • Mix Kotlin and Java code in the same project

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 you need to do is execute the following commands in a Terminal:
$ curl -s https://get.sdkman.io | bash $ bash $ sdk install kotlin 1.3.31
Alternatively, if you are using macOS and you have homebrew installed, you could run the following commands to achieve the same thing:
$ brew update
$ brew install [email protected]
Now that all of this is done, we can finally write our first Kotlin code. The application we will be writing does nothing other than display the text Hello World! on the console. Start by creating a new file named HelloWorld.kt and type the following:
fun main(args: Array<String>) { println("Hello, World!") } 
From the command line, invoke the compiler to produce the JAR assembly, as follows (include-runtime is a flag for the compiler to produce a self-contained and runnable JAR by including the Kotlin runtime in the resulting assembly):
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
Now you are ready to run your program by typing the following on your command line. Make sure that your JAVA_HOME variable is set and added to the system path:
$ java -jar HelloWorld.jar
The code is pretty straightforward. It defines the entry point function for your program, and, in the first and only line of code, it prints the text to the console.
If you have been working with the Java or Scala languages, you might raise an eyebrow because you noticed the lack of the typical class that would normally define the standard static main program entry point. How does it work then? Let's have a look at what actually happens. First, let's just compile the preceding code by running the following command. This will create a HelloWorld.class in the same folder:
$ kotlinc HelloWorld.kt
Now that we have the bytecode generated, let's look at it by using the javap tool available with the JDK, as follows (please note that the file name contains a suffix, Kt):
$ javap -c HelloWorldKt.class
Once the execution completes, you should see the following printed on your Terminal:
 Compiled from "HelloWorld.kt" public final class HelloWorldKt { public static final void main(java.lang.String[]); Code: 0: aload_0 1: ldc #9 // String args 3: invokestatic #15 // Method kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull:(Ljava/lang/Ob ject;Ljava/lang/String;)V 6: ldc #17 // String Hello, World! 8: astore_1 9: nop 10: getstatic #23 // Field java/lang/System.out:Ljava/io/PrintStream; 13: aload_1 14: invokevirtual #29 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V 17: return }
You don't have to be an expert in bytecode to understand what the compiler has actually done for us. As you can see in the snippet, a class has been generated for us, and it contains the program entry point with the instructions to print Hello World! to the console.
I would not expect you to work with the command-line compiler on a daily basis; rather, you should use the tools at hand to delegate this, as we will see shortly.

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 with its own standard class library (Kotlin runtime), which is different from the Java library. As a result, you need to merge it into the resulting JAR, or provide it in the classpath, as follows:
$ java -cp $KOTLIN_HOME/lib/kotlin-runtime.jar:HelloWorld.jar HelloWorldKt
If you develop a library for the exclusive use of other Kotlin libraries or applications, then you don't have to include the runtime. Alternatively, there is a shorter path that involves passing a flag to the Kotlin compiler, as follows:
$ kotlinc -include-runtime HelloWorld.kt -d HelloW...

Indice dei contenuti