Kotlin in Action
eBook - ePub

Kotlin in Action

Dmitry Jemerov, Svetlana Isakova

Compartir libro
  1. 360 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Kotlin in Action

Dmitry Jemerov, Svetlana Isakova

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Summary Kotlin in Action guides experienced Java developers from the language basics of Kotlin all the way through building applications to run on the JVM and Android devices. Foreword by Andrey Breslav, Lead Designer of Kotlin.Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology Developers want to get work done - and the less hassle, the better. Coding with Kotlin means less hassle. The Kotlin programming language offers an expressive syntax, a strong intuitive type system, and great tooling support along with seamless interoperability with existing Java code, libraries, and frameworks. Kotlin can be compiled to Java bytecode, so you can use it everywhere Java is used, including Android. And with an effi cient compiler and a small standard library, Kotlin imposes virtually no runtime overhead. About the Book Kotlin in Action teaches you to use the Kotlin language for production-quality applications. Written for experienced Java developers, this example-rich book goes further than most language books, covering interesting topics like building DSLs with natural language syntax. The authors are core Kotlin developers, so you can trust that even the gnarly details are dead accurate. What's Inside

  • Functional programming on the JVM
  • Writing clean and idiomatic code
  • Combining Kotlin and Java
  • Domain-specific languages


About the Reader This book is for experienced Java developers. About the Author Dmitry Jemerov and Svetlana Isakova are core Kotlin developers at JetBrains. Table of Contents

PART 1 - INTRODUCING KOTLIN

  • Kotlin: what and why
  • Kotlin basics
  • Defining and calling functions
  • Classes, objects, and interfaces
  • Programming with lambdas
  • The Kotlin type system

PART 2 - EMBRACING KOTLIN

  • Operator overloading and other conventions
  • Higher-order functions: lambdas as parameters and return values
  • Generics
  • Annotations and reflection
  • DSL construction

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 Kotlin in Action un PDF/ePUB en línea?
Sí, puedes acceder a Kotlin in Action de Dmitry Jemerov, Svetlana Isakova en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in Java. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Editorial
Manning
Año
2017
ISBN
9781638353690

Part 1. Introducing Kotlin

The goal of this part of the book is to get you productive writing Kotlin code that uses existing APIs. Chapter 1 will introduce you to the general traits of Kotlin. In chapters 2-4, you’ll learn how the most basic Java programming concepts—statements, functions, classes, and types—map to Kotlin code, and how Kotlin enriches them to make programming more pleasant. You’ll be able to rely on your existing knowledge of Java, as well as tools such as IDE coding-assistance features and the Java-to-Kotlin converter, to get up to speed quickly. In chapter 5, you’ll find out how lambdas help you effectively solve some of the most common programming tasks, such as working with collections. Finally, in chapter 6, you’ll become familiar with one of the key Kotlin specialties: its support for dealing with null values.

Chapter 1. Kotlin: what and why

This chapter covers
  • A basic demonstration of Kotlin
  • The main traits of the Kotlin language
  • Possibilities for Android and server-side development
  • What distinguishes Kotlin from other languages
  • Writing and running code in Kotlin
What is Kotlin all about? It’s a new programming language targeting the Java platform. Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code. It can be used almost everywhere Java is used today: for server-side development, Android apps, and much more. Kotlin works great with all existing Java libraries and frameworks and runs with the same level of performance as Java. In this chapter, we’ll explore Kotlin’s main traits in detail.

1.1. A taste of Kotlin

Let’s start with a small example to demonstrate what Kotlin looks like. This example defines a Person class, creates a collection of people, finds the oldest one, and prints the result. Even in this small piece of code, you can see many interesting features of Kotlin; we’ve highlighted some of them so you can easily find them later in the book. The code is explained briefly, but please don’t worry if something isn’t clear right away. We’ll discuss everything in detail later.
If you’d like to try running this example, the easiest option is to use the online playground at http://try.kotl.in. Type in the example and click the Run button, and the code will be executed.
Listing 1.1. An early taste of Kotlin
You declare a simple data class with two properties: name and age. The age property is null by default (if it isn’t specified). When creating the list of people, you omit Alice’s age, so the default value null is used. Then you use the maxBy function to find the oldest person in the list. The lambda expression passed to the function takes one parameter, and you use it as the default name of that parameter. The Elvis operator (?:) returns zero if age is null. Because Alice’s age isn’t specified, the Elvis operator replaces it with zero, so Bob wins the prize for being the oldest person.
Do you like what you’ve seen? Read on to learn more and become a Kotlin expert. We hope that soon you’ll see such code in your own projects, not only in this book.

1.2. Kotlin’s primary traits

You probably already have an idea what kind of language Kotlin is. Let’s look at its key attributes in more detail. First, let’s see what kinds of applications you can build with Kotlin.

1.2.1. Target platforms: server-side, Android, anywhere Java runs

The primary goal of Kotlin is to provide a more concise, more productive, safer alternative to Java that’s suitable in all contexts where Java is used today. Java is an extremely popular language, and it’s used in a broad variety of environments, from smart cards (Java Card technology) to the largest data centers run by Google, Twitter, LinkedIn, and other internet-scale companies. In most of these places, using Kotlin can help developers achieve their goals with less code and fewer annoyances along the way.
The most common areas to use Kotlin are:
  • Building server-side code (typically, backends of web applications)
  • Building mobile applications that run on Android devices
But Kotlin works in other contexts as well. For example, you can use the Intel Multi-OS Engine (https://software.intel.com/en-us/multi-os-engine) to run Kotlin code on iOS devices. To build desktop applications, you can use Kotlin together with TornadoFX (https://github.com/edvin/tornadofx) and JavaFX.[1]
1
“JavaFX: Getting Started with JavaFX,” Oracle, http://mng.bz/500y.
In addition to Java, Kotlin can be compiled to JavaScript, allowing you to run Kotlin code in the browser. But as of this writing, JavaScript support is still being explored and prototyped at JetBrains, so it’s out of scope for this book. Other platforms are also under consideration for future versions of the language.
As you can see, Kotlin’s target is quite broad. Kotlin doesn’t focus on a single problem domain or address a single type of challenge faced by software developers today. Instead, it provides across-the-board productivity improvements for all tasks that come up during the development process. It gives you an excellent level of integration with libraries that support specific domains or programming paradigms. Let’s look next at the key qualities of Kotlin as a programming language.

1.2.2. Statically typed

Just like Java, Kotlin is a statically typed programming language. This means the type of every expression in a program is known at compile time, and the compiler can validate that the methods and fields you’re trying to access exist on the objects you’re using.
This is in contrast to dynamically typed programming languages, which are represented on the JVM by, among others, Groovy and JRuby. Those languages let you define variables and functions that can store or return data of any type and resolve the method and field references at runtime. This allows for shorter code and greater flexibility in creating data structures. But the downside is that problems like misspelled names can’t be detected during compilation and can lead to runtime errors.
On the other hand, in contrast to Java, Kotlin doesn’t require you to specify the type of every variable explicitly in your source code. In many cases, the type of a variable can automatically be determined from the context, allowing you to omit the type declaration. Here’s the simplest possible example of this:
val x = 1
You’re declaring a variable, and because it’s initialized with an integer value, Kotlin automatically determines that its type is Int. The ability of the compiler to determine types from context is called type inference.
Following are some of the benefits of static typing:
  • Performance— Calling methods is faster because there’s no need to figure out at runtime which method needs to be called.
  • Reliability— The compiler verifies the correctness of the program, so there are fewer chances for crashes at runtime.
  • Maintainability— Working with unfamiliar code is easier because you can see what kind of objects the code is working with.
  • Tool support— Static typing enables reliable refactorings, precise code completion, and other IDE features.
Thanks to Kotlin’s support for type inference, most of the extra verbosity associated with static...

Índice