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

Buch teilen
  1. 514 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Learn Kotlin Programming

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

Stephen Samuel, Stefan Bocutiu

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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.

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Learn Kotlin Programming als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Learn Kotlin Programming von Stephen Samuel, Stefan Bocutiu im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Informatica & Programmazione. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
2019
ISBN
9781789808742

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

Inhaltsverzeichnis