ebook img

Kotlin in Action MEAP V11 PDF

363 Pages·2017·3.53 MB·English
by  
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Kotlin in Action MEAP V11

- MEAPEdition ManningEarlyAccessProgram Kotlin inAction Version11 Copyright2016ManningPublications FormoreinformationonthisandotherManningtitlesgoto www.manning.com Welcome Thanks for purchasing the MEAP for Kotlin in Action! We're looking forward to introducing you to Kotlin, which is a new programming language that is a pragmatic, safe, concise, and interoperable alternative to Java. With Kotlin, you can implement your projects with less code, a higher level of abstraction, and fewer annoyances. We assume that you're already familiar with Java, either as a server-side developer or as an Android application developer. Switching from Java to Kotlin is a smooth process that does not involve a steep learning curve, and there are many tools that can help. We expect that it won't take you long to become productive with the language. One of the strong points of Kotlin is its strong interoperability with Java. If you want to try Kotlin for yourself, you can do this in a new project, but you also have an option of introducing it into your existing Java codebase. You can also easily try features of the language in an interactive console or an online playground. The book consists of three parts. The first part will teach you the basic syntax of the language. The second part will focus on features that allow you to build reusable abstractions, higher-level functions, libraries, and even entire domain specific languages. Finally, the third part will focus on details of applying Kotlin in real-world projects, such as build system integration, Android support and concurrent programming. Both of us have been part of the team working on Kotlin for the past five years, so you can be confident that you're receiving authoritative information straight from the source. Even though version 1.0 is out, Kotlin is continuing to evolve, so we’ll ensure that the information in the MEAP book always corresponds to the current state of the language. We're looking forward to your feedback on the text that we have so far. If anything is confusing, unclear or seems to be missing entirely, please don't hesitate to leave your comments in the Author Online forum. — Dmitry Jemerov and SvetlanaIsakova brief contents PART1: INTRODUCTION 1Kotlin:WhatandWhy 2Kotlinbasics 3DefiningandCallingFunctions 4Classes,Objects,and Interfaces 5Programmingwithlambdas 6TheKotlinTypeSystem PART2: EMBRACINGKOTLIN 7OperatorOverloadingandOtherConventions 8Higher-OrderFunctions:LambdasasParametersand ReturnValues 9Generics 10 AnnotationsandReflection 11 DSLConstruction APPENDIXES: A BuildingKotlin projectsB Documenting KotlincodeC TheKotlin ecosystem 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 1.1 A taste of Kotlin First, 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. Let’s start with a small example to demonstrate what Kotlin looks like. This example defines a class, creates a collection of people, finds the oldest one, and prints the Person 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 https://try.kotl.in/. Type in the example and click the Run button, and the code will be executed. Here’s the code: data class Person(val name: String, val age: Int? = null) fun main(args: Array<String>) { val persons = listOf(Person("Alice"), Person("Bob", age = 29)) val oldest = persons.maxBy { it.age ?: 0 } println("The oldest is: $oldest") } // The oldest is: Person(name=Bob, age=29) 'data' class nullabletype (Int?);default valuefor argument top-level function named argument lambdaexpression;"elvis" operator stringtemplate autogenerated 'toString' You declare a simple data class with two properties: and . The property name age age is by default (if it isn’t specified). When creating the list of people, you omit null Alice’s age, so the default value is used. Then you use the function to find null maxBy the oldest person in the list. The lambda expression passed to the function takes one parameter, and you use as the default name of that parameter. The Elvis operator it ?: returns zero if is . Because Alice’s age isn’t specified, the Elvis operator age null replaces it with zero, so Bob wins the prize of 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 of all, 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 these: Building server-sidecode (typically, backends ofweb applications) Building mobileapplications that run onAndroid devices But Kotlin works in other contexts as well. For example, you can use the Intel Multi- 1 OS Engine to run Kotlin code on iOS devices. To build desktop applications, you can 2 use Kotlin together with JavaFX . Footnote1 https://software.intel.com/en-us/multi-os-engine Footnote2 "JavaFX:GettingStartedwithJavaFX,"Oracle,http://mng.bz/500y. In addition to Java, Kotlin can also 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 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 . The ability of the compiler to determine Int types from context is called type inference. Following are some of the benefits of static typing: Performance- Callingmethods is faster because there’s noneed to figure outat runtime which method needs to be called. Reliability-The compilerverifies thecorrectness oftheprogram, so there are fewer chances forcrashes at runtime. Maintainability-Workingwith unfamiliar codeis easier because you cansee what kind ofobjects thecode is working with. Toolsupport- Statictyping enables reliable refactorings, precisecode completion, and otherIDE features. Thanks to Kotlin’s support for type inference, most of the extra verbosity associated with static typing disappears, because you don’t need to declare types explicitly. If you look at the specifics of Kotlin’s type system, you’ll find many familiar concepts. Classes, interfaces, and generics work in a way very similar to Java, so most of your Java knowledge should easily transfer to Kotlin. Some things are new, though. The most important of those is Kotlin’s support for nullable types, which lets you write more reliable programs by detecting possible null pointer exceptions at compile time. We’ll come back to nullable types later in this chapter and discuss them in detail in chapter 6. Another new thing in Kotlin’s type system is its support for functional types. To see what this is about, let’s look at the main ideas of functional programming and see how it’s supported in Kotlin. 1.2.3 Functional and object-oriented As a Java developer, you’re no doubt familiar with the core concepts of object-oriented programming, but functional programming may be new to you. The key concepts of functional programming are as follows: First-classfunctions -You work withfunctions (pieces ofbehavior) asvalues. You can storethem in variables, pass them as parameters, orreturn them from otherfunctions. Immutability- You work with immutableobjects, which guarantees that theirstate can’t changeafter theircreation. Nosideeffects - Youusepure functions that return thesameresult given thesame inputs and don’t modify thestateofother objects or interact with theoutsideworld. What benefits can you gain from writing the code in the functional style? First, conciseness. Functional code can be more elegant and succinct compared to its imperative counterpart, because working with functions as values gives you much more power of abstraction, which lets you avoid duplication in your code. Imagine that you have two similar code fragments that implement a similar task (for example, looking for a matching element in a collection) but differ in the details (how the matching element is detected). You can easily extract the common part of the logic into a function and pass the differing parts as parameters. Those parameters are themselves functions, but you can express them using a concise syntax for anonymous functions called lambda expressions: fun findAlice() = findPerson { it.name == "Alice" } fun findBob() = findPerson { it.name == "Bob" } findPerson()contains the general logic offinding aperson. Theblock in curly braces identifies thespecific person you need to find. The second benefit of functional code is safe multithreading. One of the biggest sources of errors in multithreaded programs is modification of the same data from multiple threads without proper synchronization. If you use immutable data structures and pure functions, you can be sure that such unsafe modifications won’t happen, and you don’t need to come up with complicated synchronization schemes. Finally, functional programming means easier testing. Code without side effects is usually easier to test. Functions can be tested in isolation without requiring a lot of setup code to construct the entire environment that they depend on. Generally speaking, the functional style can be used with any programming language, including Java, and many parts of it are advocated as good programming style. But not all languages provide the syntactic and library support required to use it effortlessly; for example, this support was mostly missing from versions of Java before Java 8. Kotlin has a rich set of features to support functional programming from the get-go. These include the following: Functionaltypes,allowing functions to receiveotherfunctions as parameters orreturn otherfunctions Lambdaexpressions,lettingyou pass around blocks of codewith minimumboilerplate Data classes,providing aconcise syntax forcreating immutablevalue objects Arich set ofAPIs inthestandard library forworking with objectsand collections inthe functional style Kotlin lets you program in the functional style but doesn’t enforce it. When you need it, you can work with mutable data and write functions that have side effects without jumping through any extra hoops. And, of course, working with frameworks that are based on interfaces and class hierarchies is just as easy as with Java. When writing code in Kotlin, you can combine both the object-oriented and functional approaches and use the tools that are most appropriate for the problem you’re solving.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.