Android Development with Kotlin
eBook - ePub

Android Development with Kotlin

Marcin Moskala, Igor Wojda

Partager le livre
  1. 440 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Android Development with Kotlin

Marcin Moskala, Igor Wojda

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

Learn how to make Android development much faster using a variety of Kotlin features, from basics to advanced, to write better quality code.About This Book‱ Leverage specific features of Kotlin to ease Android application development‱ Write code based on both object oriented and functional programming to build robust applications ‱ Filled with various practical examples so you can easily apply your knowledge to real world scenarios‱ Identify the improved way of dealing with common Java patternsWho This Book Is ForThis book is for developers who have a basic understanding of Java language and have 6-12 months of experience with Android development and developers who feel comfortable with OOP concepts.What You Will Learn‱ Run a Kotlin application and understand the integration with Android Studio‱ Incorporate Kotlin into new/existing Android Java based project‱ Learn about Kotlin type system to deal with null safety and immutability‱ Define various types of classes and deal with properties‱ Define collections and transform them in functional way‱ Define extensions, new behaviours to existing libraries and Android framework classes‱ Use generic type variance modifiers to define subtyping relationship between generic types‱ Build a sample applicationIn DetailNowadays, improved application development does not just mean building better performing applications. It has become crucial to find improved ways of writing code. Kotlin is a language that helps developers build amazing Android applications easily and effectively. This book discusses Kotlin features in context of Android development. It demonstrates how common examples that are typical for Android development, can be simplified using Kotlin. It also shows all the benefits, improvements and new possibilities provided by this language.The book is divided in three modules that show the power of Kotlin and teach you how to use it properly. Each module present features in different levels of advancement. The first module covers Kotlin basics. This module will lay a firm foundation for the rest of the chapters so you are able to read and understand most of the Kotlin code. The next module dives deeper into the building blocks of Kotlin, such as functions, classes, and function types. You will learn how Kotlin brings many improvements to the table by improving common Java concepts and decreasing code verbosity. The last module presents features that are not present in Java. You will learn how certain tasks can be achieved in simpler ways thanks to Kotlin.Through the book, you will learn how to use Kotlin for Android development. You will get to know and understand most important Kotlin features, and how they can be used. You will be ready to start your own adventure with Android development with Kotlin.Style and approachA step-by-step guide that is filled with numerous real-world examples.

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Android Development with Kotlin est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Android Development with Kotlin par Marcin Moskala, Igor Wojda en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming in Java. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2017
ISBN
9781787128989
Édition
1

Classes and Objects

The Kotlin language provides full support for OOP programming. We will review powerful structures that allow us to simplify data model definition and operate on it in an easy and flexible way. We'll learn how Kotlin simplifies and improves implementations of many concepts known from Java. We will take a look at different type of classes, properties, initializer blocks, and constructors. We will learn about operator overloading and interface default implementations.
In this chapter, we will cover the following topics:
  • Class declaration
  • Properties
  • Property access syntax
  • Constructors and initializers blocks
  • Constructors
  • Inheritance
  • Interfaces
  • Data classes
  • Destructive declarations
  • Operator overloading
  • Object declaration
  • Object expression
  • Companion objects
  • Enum classes
  • Sealed classes
  • Nested classes

Classes

Classes are a fundamental building block of OOP. In fact, Kotlin classes are very similar to Java classes. Kotlin, however, allows more functionality together with simpler and much more concise syntax.

Class declaration

Classes in Kotlin are defined using the class keyword. The following is the simplest class declaration--an empty class named Person:
 class Person 
Definition of Person does not contain any body. Still, it can be instantiated using a default constructor:
 val person = Person() 
Even such a simple task as class instantiation is simplified in Kotlin. Unlike Java, Kotlin does not require the new keyword to create a class instance. Due to strong Kotlin interoperability with Java, we can instantiate classes defined in Java and Kotlin exactly the same way (without the new keyword). The syntax used to instantiate a class depends on the actual language used to create class instance (Kotlin or Java), not the language the class was declared in:
 // Instantiate Kotlin class inside Java file Person person = new Person() 
// Instantiate class inside Kotlin file var person = Person()
It is the rule of thumb to use the new keyword inside a Java file and never use the new keyword inside a Kotlin file.

Properties

Property is just a combination of a backing field and its accessors. It could be a backing field with both a getter and a setter or a backing field with only one of them. Properties can be defined at the top-level (directly inside file) or as a member (for example, inside class, interface, and so on).
In general, it is advisable to define properties (private fields with getters/setters) instead of accessing public fields directly (According to Effective Java, by Joshua Bloch, book's item 14: in public classes, use accessor methods, not public fields).
Java getter and setter conventions for private fields

Getter
: A parameterless method with a name that corresponds to property name and a get prefix (for a Boolean property there might be an is prefix used instead)

Setter: Single-argument methods with names starting with set: for example, setResult(String resultCode)
Kotlin guards this principle by language design, because this approach provides various encapsulation benefits:
  • Ability to change internal implementation without changing an external API
  • Enforces invariants (call methods that validate objects state)
  • Ability to perform additional actions when accessing member (for example, log operation)
To define a top-level property, we simply define it in the Kotlin file:
 //Test.kt val name:String 
Let's imagine that we need a class to store basic data regarding a person. This data may be downloaded from an external API (backend) or retrieved from a local database. Our class will have to define two (member) properties, name and age. Let's look at the Java implementation first:
 public class Person { private int age; private String name; public Person(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } 
This class contains only two properties. Since we can make the Java IDE generate accessors code for us, at least we don't have to write the code by ourselves. However, the problem with this approach is that we cannot get along without these automatically generated chunks, and that makes the code very verbose. We (developers) spend most of our time just reading the code, not writing it, so reading redundant code wastes a lot of valuable time. Also a simple task such as refactoring the property name becomes a little bit trickier, because the IDE might not update constructor parameter names.
Fortunately, boilerplate code can be decreased significantly by using Kotlin. Kotlin solves this problem by introducing the concept of properties that is built into the language. Let's look at a Kotlin equivalent of the preceding Java class:
 class Person { var name: String var age: Int constructor(name: String, age: Int) { this.name = name this.age = age } } 
This is an exact equivalent of the preceding Java class:
  • The constructor method is equivalent of the Java constructor that is called when an object instance is created
  • Getters and setters are generated by the Kotlin compiler
We can still define custom implementations of getters and setters. We will discuss this in more detail in the Custom getters/setters section.
All the constructors that we have already defined are called secondary constructors. Kotlin also provides alternative, very concise syntax for defining constructors. We can define a constructor (with all parameters) as part of the class header. This kind of constructor is called a primary constructor. Let's move a property declaration from the secondary constructor into the primary constructor to make our code a little bit shorter:
 class Person constructor(name: String, age: Int) { var name: String var age: Int init { this.name = name this.age = age println("Person instance created") } } 
In Kotlin, the primary constructor, as opposed to the secondary constructor, can't contain any code, so all initialization code must be placed inside the initializer block (init). An initializer block will be executed during class creation, so we can assign constructor parameters to fields inside it.
To simplify code, we can remove the initializer block and access constructor parameters directly in property initializers. This allows us to assign constructor parameters to a field:
 class Person constructor(name: String, age: Int) { var name: String = name var age: Int = age } 
We managed to make the code shorter, but it still contains a lot of boilerplate, because type declarations and property names are duplicated (constructor parameter, field assignment, and field itself). When properties does not have any custom getters or setters we can define them directly inside primary constructor by adding val or var modifier:
 class Person constructor (var name: String, var age: Int) 
Finally, if the primary constructor does not have any annotations (@Inject, and so on) or visibility modifiers (public, private, and so on), then the constructor keyword can be omitted:
 class Person (var name: String, var age: Int)
When the constructor takes a few parameters, it is good practice to define each parameter in a new line to improve code readability and decrease chance of potential merge conflicts (when merging branches from source code repository):
 class Person( var name: String, var age: Int ) 
Summing up, the preceding example is equivalent of the Java class presented at the beginning of this section--both properties are defined directly in the class primary constructor and Kotlin compiler does all the work for us--it generates appropriate fields and accessors (getters/setters).
Note that this notation contains only the most important information about this data model class--its name, parameter names, types, and mutability (val/var) information. Implementation has nearly zero boilerplate. This makes the class very easy to read, understand, and maintain.

Read-write versus read-only property

All the properties in the previous examples were defi...

Table des matiĂšres