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

  1. 514 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y 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

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Learn Kotlin Programming un PDF/ePUB en línea?
Sí, puedes acceder a Learn Kotlin Programming de Stephen Samuel, Stefan Bocutiu en formato PDF o ePUB, así como a otros libros populares de Informatica y Programmazione. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2019
ISBN
9781789808742
Edición
2
Categoría
Informatica
Categoría
Programmazione

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

Índice

  1. Title Page
  2. Copyright and Credits
  3. About Packt
  4. Contributors
  5. Preface
  6. Section 1: Fundamental Concepts in Kotlin
  7. Getting Started with Kotlin
  8. Kotlin Basics
  9. Object-Oriented Programming in Kotlin
  10. Section 2: Practical Concepts in Kotlin
  11. Functions in Kotlin
  12. Higher-Order Functions and Functional Programming
  13. Properties
  14. Null Safety, Reflection, and Annotations
  15. Generics
  16. Data Classes
  17. Collections
  18. Testing in Kotlin
  19. Microservices with Kotlin
  20. Section 3: Advanced Concepts in Kotlin
  21. Concurrency
  22. Coroutines
  23. Application of Coroutines
  24. Kotlin Serialization
  25. Other Books You May Enjoy
Estilos de citas para Learn Kotlin Programming

APA 6 Citation

Samuel, S., & Bocutiu, S. (2019). Learn Kotlin Programming (2nd ed.). Packt Publishing. Retrieved from https://www.perlego.com/book/969842/learn-kotlin-programming-a-comprehensive-guide-to-oop-functions-concurrency-and-coroutines-in-kotlin-13-2nd-edition-pdf (Original work published 2019)

Chicago Citation

Samuel, Stephen, and Stefan Bocutiu. (2019) 2019. Learn Kotlin Programming. 2nd ed. Packt Publishing. https://www.perlego.com/book/969842/learn-kotlin-programming-a-comprehensive-guide-to-oop-functions-concurrency-and-coroutines-in-kotlin-13-2nd-edition-pdf.

Harvard Citation

Samuel, S. and Bocutiu, S. (2019) Learn Kotlin Programming. 2nd edn. Packt Publishing. Available at: https://www.perlego.com/book/969842/learn-kotlin-programming-a-comprehensive-guide-to-oop-functions-concurrency-and-coroutines-in-kotlin-13-2nd-edition-pdf (Accessed: 14 October 2022).

MLA 7 Citation

Samuel, Stephen, and Stefan Bocutiu. Learn Kotlin Programming. 2nd ed. Packt Publishing, 2019. Web. 14 Oct. 2022.