Kotlin Programming Cookbook - Rashi Karanpuria - E-Book

Kotlin Programming Cookbook E-Book

Rashi Karanpuria

0,0
40,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Discover Android programming and web development by understanding the concepts of Kotlin Programming

Key Features

  • Practical solutions to your common programming problems with Kotlin 1.1
  • Leverage the functional power of Kotlin to ease your Android application development
  • Learn to use Java code in conjunction with Kotlin

Book Description

The Android team has announced first-class support for Kotlin 1.1. This acts as an added boost to the language and more and more developers are now looking at Kotlin for their application development. This recipe-based book will be your guide to learning the Kotlin programming language.

The recipes in this book build from simple language concepts to more complex applications of the language. After the fundamentals of the language, you will learn how to apply the object-oriented programming features of Kotlin 1.1. Programming with Lambdas will show you how to use the functional power of Kotlin.

This book has recipes that will get you started with Android programming with Kotlin 1.1, providing quick solutions to common problems encountered during Android app development. You will also be taken through recipes that will teach you microservice and concurrent programming with Kotlin. Going forward, you will learn to test and secure your applications with Kotlin. Finally, this book supplies recipes that will help you migrate your Java code to Kotlin and will help ensure that it's interoperable with Java.

What you will learn

  • Understand the basics and object-oriented concepts of Kotlin Programming
  • Explore the full potential of collection frameworks in Kotlin
  • Work with SQLite databases in Android, make network calls, and fetch data over a network
  • Use Kotlin's Anko library for efficient and quick Android development
  • Uncover some of the best features of Kotlin: Lambdas and Delegates
  • Set up web service development environments, write servlets, and build RESTful services with Kotlin
  • Learn how to write unit tests, integration tests, and instrumentation/acceptance tests.

Who this book is for

This book will appeal to Kotlin developers keen to find solutions for their common programming problems. Java programming knowledge would be an added advantage.

Aanand Shekhar Roy is a freelance Android developer. His mobile engineering career includes working for various startups and companies, such as Netherlands-based ConceptOffice and U.S.-based startups Consciously.Life and NextFan-FantasyIndyCar. He is also a mentor for the Associate Android Developer Fast Track program by Google on Udacity and mentors a team of 20 software developers. He is also a writer at AndroidPub. Rashi Karanpuria is a professional Android developer. She started her career by working on a wallet app for a New Zealand based Fintech startup. She has developed projects in various domains such as IOT, AdTech, Business, Social, and live streaming apps. Over the years, she has acquired a deep understanding of the user experience needed to develop a successful mobile application. She combines her design skills with scalable and maintainable code using best practices to create quality products.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 379

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Kotlin Programming Cookbook

 

 

 

 

 

 

Explore more than 100 recipes that show how to build robust mobile and web applications with Kotlin, Spring Boot, and Android

 

 

 

 

 

 

 

 

 

Aanand Shekhar Roy
Rashi Karanpuria

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Kotlin Programming Cookbook

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Merint MathewAcquisition Editor: Isha RavalContent Development Editor: Onkar WaniTechnical Editor: Sachin SunilkumarCopy Editor: Shaila KusanaleProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Rekha NairGraphics: Jason MonteiroProduction Coordinator: Nilesh Mohite

First published: January 2018

Production reference: 1230118

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78847-214-2

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the authors

Aanand Shekhar Roy is a freelance Android developer. His mobile engineering career includes working for various startups and companies, such as Netherlands-based ConceptOffice and U.S.-based startups Consciously.Life and NextFan-FantasyIndyCar. He is also a mentor for the Associate Android Developer Fast Track program by Google on Udacity and mentors a team of 20 software developers. He is also a writer at AndroidPub.

Acknowledgement is probably that part of the book you least have interest in. Simply because every time you open it, it's either thanking someone else who you don't know.  Not this time, this book is dedicated to only learners like you, simply because it wouldn't have come to life without you wanting to read it.

 

 

Rashi Karanpuria is a professional Android developer. She started her career by working on a wallet app for a New Zealand based Fintech startup. She has developed projects in various domains such as IOT, AdTech, Business, Social, and live streaming apps. Over the years, she has acquired a deep understanding of the user experience needed to develop a successful mobile application. She combines her design skills with scalable and maintainable code using best practices to create quality products.

I would like to thank each & every member of the developer community all across the world. This is the only community that I know of to give ideas and resources so freely without expecting anything in return. Did you know Kotlin is open source? This giving nature of our developer community is why I am who I am today. Thanks.

 

About the reviewer

Mitchell Wong Ho was born in Johannesburg, South Africa, where he completed his national diploma in electrical engineering. Mitchell's software development career started on embedded systems and then moved to Microsoft desktop/server applications.Mitchell has been programming in Java since 2000 on J2ME, JEE, desktop, and Android applications, and has more recently been advocating Kotlin for Android.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Sections

Getting ready

How to do it…

How it works…

There's more…

See also

Get in touch

Reviews

Installation and Working with Environment

Introduction

Creating Kotlin Android project

Getting ready

How to do it...

There's more...

How to use Gradle to run Kotlin code

Getting ready

How to do it...

There's more...

See also

How to run a Kotlin compiled class

Getting ready

How to do it...

How it works...

There's more...

How to build a self-executable JAR with Gradle and Kotlin

Getting ready

How to do it...

How it works...

Reading console input in Kotlin

Getting ready

How to do it...

How it works...

Converting Java code to Kotlin and vice versa

Getting ready

How to do it...

How it works...

How to write an idiomatic logger in Kotlin

Getting ready

How to do it...

How it works...

There's more...

See also

Escaping for Java identifiers that are keywords in Kotlin

Getting ready

How to do it...

How it works...

Disambiguating using the "as" keyword to locally rename the clashing entity

Getting ready

How to do it...

Doing bit manipulations in Kotlin

Getting ready

How to do it...

Or

and

xor

inv

shl

shr

ushr

How it works...

Parsing String to Long, Double, or Int

Getting ready

How to do it...

Converting String to Long

Converting string to Long using string.toLongOrNull()

Converting with special radix

Parsing string to Long with special radix

How it works...

There's more...

Using String templates in Kotlin

How to do it...

How it works...

There’s more...

Control Flow

Introduction

Assigning result to an expression using the if keyword

Getting ready

How to do it...

There's more...

Using range with the when expression

Getting ready

How to do it...

How it works...

There's more...

Using when with custom objects

Getting ready

How to do it...

How it works...

Using try–catch as an expression

Getting ready

How to do it...

How it works...

There's more...

How to write a swap function in Kotlin using the also function

Getting ready

How to do it...

How it works...

There's more...

How to throw a custom exception in Kotlin

Getting ready

How to do it...

How it works...

How to make a multiconditional loop in Kotlin

Getting ready

How to do it...

How it works...

Classes and Objects

Introduction

Initializing body of constructor

Getting ready

How to do it...

Converting one data type into another

Getting ready

How to do it...

How it works...

How to type check an object

Getting ready

How to do it...

How it works...

There's more...

How to work with an abstract class in Kotlin

Getting ready

How to do it...

How it works...

How to iterate over a class's properties in Kotlin

Getting ready

How to do it...

How it works...

There's more...

How to work with inline properties

Getting ready

How to do it...

How it works...

How to work with nested class

Getting ready

How to do it...

How it works...

There's more...

Getting class in Kotlin

How to do it...

There's more...

Working with delegated properties

Getting ready

How to do it...

There's more...

Working with enums

Getting ready

How to do it...

There's more...

Functions

Introduction

Specifying default values in functions

Getting ready

How to do it...

There's more...

Using named arguments in functions

Getting ready

How to do it...

Creating the RecyclerView Adapter in Kotlin

Getting ready

How to do it...

How it works...

There's more...

Creating getter setters in Kotlin

Getting ready

How to do it...

There's more...

Passing variable arguments to a function

Getting ready

How to do it...

How it works...

There's more...

Passing a function as a parameter to another

Getting ready

How to do it...

How it works...

Declaring a static function

Getting ready

How to do it...

Using the use keyword in Kotlin

Getting ready

How to do it...

How it works...

Working with closures

Getting ready

How to do it...

There's more...

Function literals with receivers

Getting ready

How to do it...

Working with anonymous functions

Getting ready

How to do it...

Object-Oriented Programming

Introduction

Working with interfaces in Kotlin

Getting ready

How to do it…

There's more…

How to implement complicated interfaces with multiple overridden methods in Kotlin

Getting ready

How to do it…

How to extend a class in Kotlin (Inheritance and Extension functions)

Getting ready

How to do it…

Extension functions

How it works…

There's more…

How to work with Generics in Kotlin

Getting ready

How to do it…

There's more…

How to implement polymorphism in Kotlin

Getting ready

How to do it…

Restricting class hierarchies

Getting ready

How to do it…

How it works…

There's more…

Collections Framework

Introduction

How to merge two collections

Getting ready

How to do it…

Splitting original collection into pair of collections

Getting ready

How to do it…

How it works…

There's more…

Sorting a list by specified comparator

Getting ready

How to do it…

How it works…

Sorting in descending order

Getting ready

How to do it…

How it works…

Parsing a JSON response using Gson

Getting ready

How to do it…

There's more…

How to filter and map using lambda expressions

Getting ready

How to do it…

How to sort a list of objects and keep null objects at the end

Getting ready

How to do it…

How it works…

How to implement a lazy list in Kotlin

Getting ready

How to do it…

How it works…

How to pad a string in Kotlin

Getting ready

How to do it…

How it works…

How to flatten an array or map

Getting ready

How to do it…

How it works…

How to sort collection by multiple fields in Kotlin

Getting ready

How to do it…

How it works…

How to use limit in Kotlin list

Getting ready

How to do it…

How to create a 2D array in Kotlin

Getting ready

How to do it…

There's more…

How to skip the first "n" entries in Kotlin

Getting ready

How to do it…

How it works…

Handling File Operations in Kotlin

Introduction

Reading from files using InputReader

Getting ready

How to do it…

How it works…

There's more…

Reading all lines in a file using InputReader

Getting ready

How to do it…

How it works…

Reading line by line using InputReader

Getting ready

How to do it…

How it works…

Reading from files using BufferedReader

Getting ready

How to do it…

How it works…

Reading all lines in a file using BufferedReader

Getting ready

How to do it…

How it works…

Reading line by line using bufferedReader

Getting ready

How to do it…

How it works…

There's more…

Reading string and JSON over network

Getting ready

How to do it…

How it works…

Anko Commons and Extension Function

Introduction

Setting up Anko with Gradle

Getting ready

How to do it…

Extending Android framework using extension function

Getting ready

How to do it…

How it works…

There's more…

Using extensions as properties

Getting ready

How to do it…

How it works…

There's more…

Using intents with Anko

Getting ready

How to do it…

How it works…

Making a call intent using Anko

Getting ready

How to do it…

How it works…

Sending a text intent using Anko

Getting ready

How to do it…

How it works…

Browsing the web browser using Anko

Getting ready

How to do it…

How it works…

Sharing some text using intents in Anko

Getting ready

How to do it…

How it works…

Sending an email using Anko

Getting ready

How to do it…

How it works…

Creating Android dialogs with Anko

Getting ready

How to do it…

Showing an alert dialog with a list of text items

Getting ready

How to do it…

How it works…

Using Anko in Views

Getting ready

How to do it…

Logging using Anko

Getting ready

How to do it…

Handling dimensions with Anko

Getting ready

How to do it…

Version checking on Android

Getting ready

How to do it…

How it works…

Anko Layouts

Introduction

Setting up Anko library for Anko layouts in Gradle

Getting ready

How to do it…

How it works…

There's more…

Creating user-interface programmatically

Getting ready

How to do it…

How it works…

Working with the old code of XML layouts

Getting ready

How to do it…

How it works…

There's more…

Using the provided AnkoComponent interface

Getting ready

How to do it…

How it works…

There's more…

Setting theme for Android views in Anko

Getting ready

How to do it…

Setting layout parameters for Anko views

Getting ready

How to do it…

How it works…

Adding listeners to Anko views

Getting ready

How to do it…

How it works…

There's more…

Inserting XML layouts into DSL

Getting ready

How to do it…

Converting XML files into DSL

Getting ready

How to do it…

Showing Snackbar

Getting ready

How to do it…

Showing Toasts

Getting started

How to do it…

Accessing views using synthetic properties

Getting ready

How to do it…

Accessing views of view groups using extension functions

Getting ready

How to do it…

How it works...

Databases and Dependency Injection

Introduction

Using SQLite database in Kotlin

Getting ready

How to do it…

Creating database tables

Getting ready

How to do it…

Injecting dependencies in Kotlin

Getting ready

How to do it…

How it works…

Reading data from database

Getting ready

How to do it…

Converting database cursor into list of objects

Getting ready

How to do it…

Using parseOpt for nullable object

Getting ready

How to do it…

Inserting data into database

Getting ready

How to do it…

Creating singletons in Kotlin

Getting ready

How to do it…

How it works…

Using Dagger 2 with Kotlin

Getting ready

How to do it…

Using Butterknife with Kotlin

Getting ready

How to do it…

There's more…

Networking and Concurrency

Introduction

How to fetch data over network

Getting ready

How to do it…

There's more…

How to create data class in Kotlin

Getting ready

How to do it…

There's more…

How to copy data class with modifications

Getting ready

How to do it…

There's more…

How to parse JSON data from network to data class

Getting ready

How to do it…

How to download a file in Kotlin

Getting ready

How to do it…

How to use RxJava and Retrofit with Kotlin

Getting ready

How to do it…

How to make an endless list using RecyclerView

Getting ready

How to do it…

How it works…

How to use Anko to run background tasks with Kotlin in Android

Getting ready

How to do it…

How it works…

How to use coroutines to achieve multithreading

Getting ready

How to do it…

There's more…

Lambdas and Delegates

Introduction

Click listeners using lambdas

Getting ready

How to do it…

How it works…

There's more…

Using lazy delegate in Kotlin

Getting ready

How to do it…

How it works…

Using the observable delegate

Getting ready

How to do it…

There's more…

Using vetoable delegate

Getting ready

How to do it…

How it works…

There's more…

Writing your own delegates

Getting ready

How to do it…

How it works…

Using the lateinit modifier

Getting ready

How to do it…

There's more…

Working with SharedPreferences

Getting ready

How to do it…

There's more…

Creating a chain of multiple lets in Kotlin

Getting ready

How to do it…

Creating global variables

Getting ready

How to do it…

Testing

Introduction

Unit testing Kotlin code

Getting ready

How to do it…

How it works…

Unit testing with Mockito

Getting ready

How to do it…

There's more…

Spy object

Mockito limitations

Running instrumentation tests

Getting ready

How to do it…

There's more…

Writing JUnit rules in Kotlin (@Rule)

Getting ready

How to do it…

How it works…

Acceptance tests using Espresso Kotlin

Getting ready

How to do it…

There's more…

Writing assertEquals in Kotlin

Getting ready

How to do it…

Web Services with Kotlin

Introduction

How to run the application on Tomcat

How to do it…

Setting up dependencies for building RESTful services

Getting ready

How to do it…

How to create a REST controller

Getting ready

How to do it…

There's more…

Creating the Application class for Spring Boot

Getting ready

How to do it…

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Kotlin Cookbook will be a go-to guide to problems new Kotlin developers get stuck with. Along with that, Kotlin Cookbook will also help developers learn handy tricks and concepts that they may need while coding. This book will also help developers uncover the full potential of an amazing programming language, that is, Kotlin.

The book starts with an overview of Kotlin and moves on to some great simple concepts and features that Kotlin offers. From there, it will move on to OOP fundamentals and creating simple Android applications. Next will be the recipes for more complicated concepts such as networking, database, architectures, file io, and testing. It will also cover some great features of Anko that really eases out some complicated concepts in Android development, making it faster and more fun. Last will be some miscellaneous but extremely useful recipes that developers might need from time to time.

Who this book is for

This book is targeted at Kotlin beginners who know Android and Java Development and who have a good knowledge level and understanding of the Android development cycle. The readers are familiar with the concepts of Android development and understand the needs of testing their code. They want to learn efficient Kotlin techniques in order to make the existing Android development process more efficient and fun. This is not an introductory book for Kotlin, and it assumes basic familiarity with Kotlin. This book aims at helping developers solve issues they are stuck with while working with Kotlin.

What this book covers

Chapter 1, Installation and Working with Environment, walks you through starting with a Kotlin project. We will also introduce you to the Gradle build system and help you in setting up your development environment.

Chapter 2, Control Flow, includes recipes for control flow in Kotlin. Kotlin has brought a lot of power to old control flows, as you can now use them as an expression. Kotlin has also introduced a powerful "when", which is basically Java’s "switch" improvements.

Chapter 3, Classes and Objects, says that classes and objects are inevitable parts of object-oriented programming. This chapter will include the solutions and examples of real-world problems faced by developers and how Kotlin solves it. This chapter will also lay the foundation to the upcoming chapter OOPS programming with Kotlin.

Chapter 4, Functions, informs that functions are inevitable parts of object-oriented programming. This chapter will include the solutions and examples of real-world problems faced by developers and how Kotlin solves it.

Chapter 5, Object-Oriented Programming, builds upon the learning of Chapter 3, Classes and Objects, and will include recipes that help in OOP.

Chapter 6, Collections Framework, presents the recipes that will explore the full potential of Collection framework in Kotlin.

Chapter 7, Handling File Operations in Kotlin, covers recipes about basic I/O and File I/O.

Chapter 8, Anko Commons and Extension Function, contains recipes on how to use the Anko library of Kotlin for efficient and quick Android development.

Chapter 9, Anko Layouts, has recipes on how to use the Anko library of Kotlin for efficient and quick Android development.

Chapter 10, Databases and Dependency Injection, dives into recipes to work with SQLite databases in Android.

Chapter 11, Networking and Concurrency, discusses recipes that will help developers make network calls and fetch data over a network.

Chapter 12, Lambdas and Delegates, uncovers some of the best (and difficult) features of Kotlin, that is, Lambdas and Delegates. This contains recipes to help the developers get started with them.

Chapter 13, Testing, outlines concepts on writing tests in Kotlin while touching Unit tests, integration tests, instrumentation, and acceptance tests.

Chapter 14, Web Services with Kotlin, helps developers write web services using Kotlin language.

To get the most out of this book

This book assumes familiarity with Java and Android development. This is not an introductory book for learning Kotlin. Readers must have used Android studio because many of the recipes will be focused toward Android development.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitLab athttps://gitlab.com/users/aanandshekharroy/projects. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

 

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The corresponding sourceSets property should be updated if not using the default convention."

A block of code is set as follows:

sourceSets { main.kotlin.srcDirs += 'src/main/myKotlin' main.java.srcDirs += 'src/main/myJava'}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

sourceSets {

main.java.srcDirs += 'src/main/kotlin/'

}

Any command-line input or output is written as follows:

$ kotlinc hello.kt -include-runtime -d hello.jar.

$ java -jar hello.jar

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In the Select Deployment Target window, select your device, and click on OK."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows:

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Installation and Working with Environment

The following recipes will be covered in this chapter:

Creating Kotlin Android project

How to use Gradle to run Kotlin code

How to run a Kotlin compiled class

How to build a self-executable jar with Gradle and Kotlin

Reading console input in Kotlin

Converting Java code to Kotlin and vice versa

How to write an idiomatic logger with Kotlin

Escaping for Java identifiers that are keywords in Kotlin

Disambiguating using the "as" keyword to locally rename the clashing entity

Doing bit manipulations in Kotlin

Parsing String to Long, Double, or Int

Using String templates in Kotlin

Introduction

Android apps are a fascinating piece of technology. The apps developed on Android have worldwide appeal and audience. However, that has posed serious challenges for developers. The challenge is with updating APIs, platforms, and varied device capabilities. For example, if you are an Android developer, you have to rely on Java 6 if you want to support all API levels in Android. Java 6 is obsolete now, so much so that even its successor, Java 7, is kind of obsolete today. There was a great need for modern language for Android, which has built a trillion dollar industry around it and has influenced billions of lives. True, we have Java 8 now, but we can only use it if we are developing Android apps for API level 24 and above. However, that’s equivalent to targeting only 9% of Android devices as of 2017; clearly, this isn’t the way to go.

All is not lost though, and thanks to the JVM, we can write Android apps using any language that produces JVM compatible bytecode on compilation. So theoretically, we can use Clojure, Groovy, Scala, and Kotlin, but Kotlin is the best alternative among all, why? It's because in April 2017, Google announced Kotlin as an official language for Android development.

Some of the biggest tech companies such as Pinterest, Uber, Atlassian, Coursera, and Evernote are now using Kotlin in their Android apps. This wide adoption by them already speaks a huge volume for Kotlin. The 100% interoperability with Android and Java has helped Kotlin in its adoption. Kotlin is much easier to work with than Java and, apart from Android apps, you can also build web-apps with it. So, this chapter will introduce you to Kotlin and help you get started with this awesome piece of technology.

In this chapter, we will first see how to set up the environment to begin working with Kotlin.

Creating Kotlin Android project

Getting started with Kotlin is really easy, especially after Google has added official support for the language. You can use Kotlin directly with Android Studio 3. Android Studio 3 is still in Beta version at the time of writing this book. The best thing about using Kotlin for Android is that it is interoperable with your existing code, be it Java or C++. While working with Kotlin, you will realize that code in Kotlin is concise, extensible, and powerful. It really makes Android development more fun. Let's see how we can start working in Kotlin by first creating a Kotlin project in Android Studio 3.

Getting ready

To get started with this recipe, you will need Android Studio installed on your computer. Android Studio has both Android SDK and Android Virtual device in it. Ensure that you have Java Development Kit installed on your system. You will need an android phone or Emulator for debugging your project. You will also need at least one Android Virtual Device installed, of your desired specifications if you are not using an Android phone.

So basically, here's the checklist of the things that need to be installed before you move on to the next section:

Java Development Kit (use the latest)

Android Studio 3+

Android phone or emulator

How to do it...

Creating a project in Android Studio is very simple and to create it in Kotlin just requires one extra click. Here's a step-by-step process of doing it:

In Android Studio, in the menu, click on

File

|

New

|

New Project

. Alternatively, if you've just opened Android Studio and see the Welcome to Android Studio window, click on

Start a new Android Studio project

.

In the wizard, add your Application name and Company domain, and simply check the box that says

Include Kotlin support

. Click on 

Next

:

On the next screen, you will be asked to choose your target devices and the minimum SDK support. So basically, it asks things like, "Do you want the application to run on both phone and android wear?" and "Do you want to support from Jelly Bean up or KitKat and up?":

 On the next screen, you will be prompted to

Add an Activity

to the project. You can also skip this step and add an activity later, but for now, just click on a

Basic Activity

 and click on 

Next

. If you have also chosen

Wear

or any other option, you will be prompted to add activity for those components as well:

Next, you will be prompted to

Configure the Activity

you added. Basically, what you have to do is to provide

Activity Name, Layout Name,

and

Title

. After this, click on

Finish

, because you are done with creating your first project in Kotlin.

Run project on your device: You need to follow these steps:

Connect your device to your development machine with a USB cable.

Enable USB debugging on your device by going to

Settings

|

Developer options

.

On Android 4.2 and newer, Developer options are hidden by default. To make it available, go to Settings | About phone and tap on Build number seven times. Return to the previous screen to find Developer options.

Now in your Android Studio, click on the app module in the Project window and then select Run (or click on Run in the toolbar).

In the Select Deployment Target window, select your device, and click on OK. After a while, you will see the application running on your mobile or an emulator.

There's more...

After clicking on the Finish button in the Create New Project window, Android Studio will configure things and create your project. If you added an activity as mentioned in Step 4, you will be greeted with the boilerplate code of the activity. It looks something like this:

How to use Gradle to run Kotlin code

Gradle has now become the de facto build tool for Android, and it is very powerful. It’s great for automating tasks without compromising on maintainability, usability, flexibility, extensibility, or performance. In this recipe, we will see how to use Gradle to run Kotlin code.

Getting ready

We will be using IntelliJ IDEA because it provides great integration of Gradle with Kotlin, and it is a really great IDE to work on. You can also use Android Studio for it.

There's more...

The default structure of the project, when you create a new project in IntelliJ, is as illustrated:

project - src - main (root) - kotlin - java

If you want to have a different structure of the project, you should declare it in build.gradle. You can do it by adding the following lines in build.gradle.

The corresponding sourceSets property should be updated if not using the default convention:

sourceSets { main.kotlin.srcDirs += 'src/main/myKotlin' main.java.srcDirs += 'src/main/myJava'}

Though you can keep Kotlin and Java files under the same package, it’s a good practice to keep them separated.

See also

Check out the How to build a self-executable jar with Gradle and Kotlin recipe in this chapter.

How to run a Kotlin compiled class

Working with the command-line compiler for any language is one of the first steps to get a better understanding of the language, and this knowledge comes handy at a lot of times. In this recipe, we will run a Kotlin program using the command line, and we will also play a bit with the interactive shell of Kotlin.

Getting ready

To be able to perform this recipe, you need a Kotlin compiler installed on your development machine. Every Kotlin release ships with a standalone compiler. You can find the latest release at https://github.com/JetBrains/kotlin/releases.

To manually install the compiler, unzip the standalone compiler into a directory and optionally, add the bin directory to the system path. The bin directory contains the scripts needed to compile and run Kotlin on Windows, OS X, and Linux.

How to do it...

Now we are ready to run our first program using the command line. First, we will create a simple application that displays Hello World! and then compile it:

Create a file with the name

hello.kt

and add the following lines of code in that file:

fun main(args: Array<String>) { println("Hello, World!") }

Now we compile the file using the following command:

$ kotlinc hello.kt -include-runtime -d hello.jar

Now we run the application using the following command:

$ java -jar hello.jar

Suppose you want to create a library that can be used with other Kotlin applications; we can simply compile the Kotlin application in question into

.jar

executable without the

-include-runtime

option, 

that is, the new command will be as follows:

$ kotlinc hello.kt -d hello.jar

Now, let's check out the Kotlin interactive shell. Just run the Kotlin compiler without any parameters to have an interactive shell. Here's how it looks:

Hopefully, you must have noticed the information I am always guilty of ignoring, that is, the command to quit interactive shell is :quit and for help, it is :help.

You can run any valid Kotlin code in the interactive shell. For example, try some of the following commands:

3*2+(55/5)

println("yo")

println("check this out ${3+4}")

Here's a screenshot of running the preceding code:

How it works...

The -include-runtime option makes the resulting .jar file self-contained and runnable by including the Kotlin runtime library in it. Then, we use Java to run the .jar file generated.

The -d option in the command indicates what we want the output of the compiler to be called and maybe either a directory name for class files or a .jar filename.

There's more...

Kotlin can also be used for writing shell scripts. A shell script has top-level executable code.

Kotlin script files have the .ktsextension as opposed to the usual .kt for Kotlin applications.

To run a script file, just pass the -script option to the compiler:

$ kotlinc -script kotlin_script_file_example.kts

How to build a self-executable JAR with Gradle and Kotlin

Kotlin is great for creating small command-line utilities, which can be packaged and distributed as normal JAR files. In this recipe, we will see how to do it using Gradle build system. Gradle build system is one of the most sophisticated build systems out there. It is the default build tool for Android and is designed to ease scripting of complex, multilanguage builds with a lot of dependencies (typical of big projects). It achieves the goal of automating your project without compromising on maintainability, usability, flexibility, extensibility, or performance. We will be using Gradle build system to create a self-extracting JAR file. This JAR file can be distributed to and run on any platform supporting Java.

Getting ready

You need an IDE (preferably IntelliJ or Android Studio), and you need to tell it where your Kotlin files are present. You can do so by specifying it in the build.gradle file by adding the following:

sourceSets { main.java.srcDirs += 'src/main/kotlin/'}

The preceding lines are required if you have your Kotlin files separated from Java packages. This is optional, and you can continue working with Kotlin files under Java packages, but it’s a good practice to keep them separated.

We’ll be creating a very simple function that just prints Hello World! when executed. Since it’ll be a simple function, I am just adding it as a top-level main() function.

How to do it...

Let's go through these steps, with which we can create a self-executable JAR:

We’ll create a simple class 

HelloWorld.kt

having the main function, which just prints out “Hello world!”:

fun main(args:Array<String>){ println("Hello world")}

Now we need to configure a 

jar

task, which Gradle build goes through to inform it of our entry to our project. In a Java project, this will be the path to the class where our

main()

function resides, so you will need to add this

jar

task in

build.gradle

:

jar { manifest { attributes 'Main-Class': 'HelloWorldKt' } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }}

After adding the preceding snippet to 

build.gradle

, you need to run the following gradle command to create the jar file:

./gradlew clean jar

The created jar file can be found in the

build/libs

folder. Now you can just run the

java -jar demo.jar

command 

to run the JAR file.

After you do that, you can see the output in the console:

How it works...

To make self-executable JARs, we need a manifest file called MANIFEST.MF in the META-INF directory. For our purposes here, we just need to specify the name of the Java class that contains the Java-based extractor program's main() method.

One might argue that even though we don’t have top-level class declaration, we are specifying it as HelloWorldKt in the code for the jar task:

manifest { attributes 'Main-Class': 'HelloWorldKt' }

The reason for putting the preceding code block in the jar task is that Kotlin compiler adds all top-level functions to respective classes for back-compatibility with JVM. So, the class generated by Kotlin compiler will have the filename, plus the Kt suffix, which makes it HelloWorldKt.

Also, the reason we added from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } in jar task is because we want Gradle to copy all of a JAR’s dependencies. The reason for doing so is that, by default, when Gradle (as well as Maven) packs some Java class files into a JAR file, it assumes that this JAR file will be referenced by an application, where all of its dependencies are also accessible in the classpath of the loading application. So, by specifying the preceding lines in jar task, we are telling gradle to take all of this JAR’s referenced dependencies and copy them as part of the JAR itself. In the Java community, this is known as a fat JAR