Kotlin in Action
eBook - ePub

Kotlin in Action

Dmitry Jemerov, Svetlana Isakova

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

Kotlin in Action

Dmitry Jemerov, Svetlana Isakova

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul 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

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.
Kotlin in Action è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Kotlin in Action di Dmitry Jemerov, Svetlana Isakova in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in Java. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Editore
Manning
Anno
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...

Indice dei contenuti