41,99 €
Get to know the building blocks of Kotlin and best practices when using quality world-class applications
This practical guide is for programmers who are already familiar with Kotlin. If you are familiar with Kotlin and want to put your knowledge to work, then this is the book for you. Kotlin programming knowledge is a must.
Kotlin is a powerful language that has applications in a wide variety of fields. It is a concise, safe, interoperable, and tool-friendly language. The Android team has also announced first-class support for Kotlin, which is an added boost to the language. Kotlin's growth is fueled through carefully designed business and technology benefits.
The collection of projects demonstrates the versatility of the language and enables you to build standalone applications on your own. You'll build comprehensive applications using the various features of Kotlin. Scale, performance, and high availability lie at the heart of the projects, and the lessons learned throughout this book.
You'll learn how to build a social media aggregator app that will help you efficiently track various feeds, develop a geospatial webservice with Kotlin and Spring Boot, build responsive web applications with Kotlin, build a REST API for a news feed reader, and build a server-side chat application with Kotlin.
It also covers the various libraries and frameworks used in the projects. Through the course of building applications, you'll not only get to grips with the various features of Kotlin, but you'll also discover how to design and prototype professional-grade applications.
Each chapter is independent and focuses on a unique technology, where Kotlin is used to build an example application. Together the chapters cover a full spectrum.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 258
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: December 2017
Production reference: 1071217
ISBN 978-1-78839-080-4
www.packtpub.com
Authors
Ashish Belagali
Hardik Trivedi
Akshay Chordiya
Copy Editor
Safis Editing
Reviewer
Alexander Hanschke
Project Coordinator
Prajakta Naik
Commissioning Editor
Richa Tripathi
Proofreader
Safis Editing
Acquisition Editor
Sandeep Mishra
Indexer
Rekha Nair
Content Development Editor
Akshada Iyer
Graphics
Jason Monteiro
Technical Editor
Adhithya Haridas
Production Coordinator
Melwyn Dsa
Ashish Belagali is an IIT Bombay alumnus with 24 years of experience in software technology, management, consulting, and client handling. He has successfully executed offshore engagements in both onsite and offshore roles. He is known as a turnaround specialist, having turned many IT projects from red to green in a short time.
In spite of the senior positions he has handled, Ashish loves coding and has managed to stay hands-on with it. He often speaks about technology, entrepreneurship, and work effectiveness. He is a Kotlin enthusiast and has worked on several Kotlin projects. He is also the founder of the Kotlin Pune User Group.
Hardik Trivedi is a self-taught computer program writer. He has extensively worked on Android and Java since 2010 and has also immersed himself in Kotlin and JavaScript. When he is not working on client projects, he loves contributing back to the development community by spending time on stack overflow and writing tech blogs.
Hardik also mentors college students, professionals, and companies who have a keen interest in mobile app development. He is also an active community speaker. Someday in the future, you may find him owning a restaurant and serving exquisite cuisines to his customers.
Akshay Chordiya is the co-founder of BitFurther, an Android Developer by heart, and a Kotlin enthusiast. He has been working with Android for over 4 years. He is an active community speaker who is mostly found talking about Android and Kotlin.
Akshay is an avid blogger and instructor. He has a love for anything with the word "technology" in it! The vision of bringing about a change in the world through his knowledge is what makes him get out of bed every day and work on his apps and his start-up. "Doing what you love" can be said to sum up his life until now and in the exciting years to come ahead!
For me, the first thanks goes not to a person, but to a company. It is Google who inadvertently played a big role in this book. Google's announcement about Kotlin made me curious about Kotlin. I liked it more as I learned it. When I created the Pune Kotlin User Group without any publicity, many good programmers and students joined it out of their own interest. Then, at a Google Developer Group meet, I met Akshay and Hardik, who later became the co-authors of this book. Thus, again, it's Google who brought us together.
Writing this book was a journey. Finding time from our day job was not easy. There were ups and downs. But the team sailed through that because of a good camaraderie. Whenever one of us seemed to fall behind schedule, another one volunteered to chip in. There were healthy discussions on the content, which was made possible through the ability to respect and accept the other person's viewpoint.
I would like to thank my family who accommodated our erratic schedules. At times, after a long day at work, I would again open my laptop and work beyond midnight. My family understood and supported me.
I would also like to thank Captain D. P. Apte for his guidance. He has recently published a book, and his guidance was valuable in the initial stages when Packt started speaking to me about writing this book.
Finally, I would like to thank the Packt team for their guidance and patience. Working with Sandeep Mishra, Akshada Iyer, Adhithya Haridas, and Venkatesh Pai was a pleasure. We especially found that Akshada's comments were always inspiring and her appreciation kept up our spirits while writing the book. I am sure there were other people in the background who we just know as "the team". We noticed that "the team" was eager to help us and had a quick response time whenever the book needed it. It helped in issue resolution, and that made us sail through this journey with a good deal of ease.
– Ashish Belagali
Alexander Hanschke is a CTO at techdev Solutions GmbH, a technology company located in Berlin. He had worked on various Java-based projects in the financial industry over the last 8 years, before turning to Kotlin in 2016. Since then, he has applied Kotlin to all kinds of projects, including Alexa skills, blockchain clients, and Spring-based applications. He frequently speaks at technology meetups and occasionally writes articles about the various aspects of the Kotlin programming language.
For support files and downloads related to your book, please visit www.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.
www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand
and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788390806.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
The Power of Kotlin
Kotlin – a better Java
Why not other languages?
Why Kotlin?
Concise yet expressive code
Enhanced robustness
Excellent IDE support from day one
Beyond being a better Java
Kotlin is in the winning camp
Go native strategy
Kotlin's winning strategy
Summary
Geospatial Messenger – Spring Boot
Why Spring Boot?
Leveraging Kotlin in Spring Boot applications
Extension functions
Constructor injection
Leveraging Null safety
Functional bean declaration DSL
Let's build our geospatial messenger
Preview
Features
Architecture
Setting up the IDE
Creating a project
Project structure
Setting up the build script
Adding Kotlin dependency
Adding Spring Boot dependencies
Exposed library
Gradle dependency
Defining the table
Connecting to the database
CRUD operations
Explaining PostGIS
Installation
Gradle dependency
Object mapping
Gradle dependency
Completing the Gradle script
Coding the application
Frontend
HTML
CSS
JavaScript
Rendering the map
Plotting messages on the map
Listening to message saved events
Complete JavaScript
Application class
Backend
Application configuration
Data classes
Exposed integration
Exposed objects
Extras for geospatial support
Service/Controller
Repository
CrudRepository
Event broadcaster
Extension functions
Testing
Gradle dependency
Test cases
Pro-tips
All-open compiler plugin
Spring starter
Playing with the Java to Kotlin converter
Migrating to Kotlin
Should I rewrite the existing Java code in Kotlin?
What if I want to rewrite Java to Kotlin?
Summary
Social Media Aggregator Android App
Setting up Kotlin
Setting up the Kotlin plugin for Android Studio
Getting started
Converting Java code to Kotlin code
Creating a social media aggregator
Using datatypes and conversion
String interpolation
String utility methods
Classes
Constructors
Data classes
Inheritance
Singletons
lateinit versus lazy initialization
lateinit
The lazy property
Control flow
The when() expression
Getters and setters
Declaring a property
Interfaces
Kotlin Android extension
Ditching the findViewById() method
View extensions
Fragment LayoutInflater extension
The Standard.kt function
The with() function
The apply() function
The let() function
Functions in Kotlin
Single-expression function
Inline function
Default and named parameters
Default parameter
Named parameter
Destructing declaration
Android context
Null-Safety
Why Kotlin is called null-safe
Safe call operator (?.)
Elvis operator (?:)
Force unwrap (!!)
Smart casts
The is and !is operators
The as operator
Companion object
Fragment instantiation using companion objects
Dealing with constants
Object expressions and declarations
Delegated properties
Dealing with Shared Preferences
Setting up an item click on RecyclerView
Anko - Kotlin's buddy for Android
Setting up Anko
Displaying toast()
Starting an activity made easy
Anko layout
Summary
Weather App Using Kotlin for JavaScript
Creating your first Kotlin and JavaScript project
Choosing an IDE
Creating a project
Creating an HTML page
Creating a Main.kt file
Running the project
Developing a weather forecast web app
Creating a UI with dummy data
Simple HTML approach
Creating UI using Kotlin
What is DSL?
Using Kotlinx.html
Refactoring the HTML code using DSL
Calling a weather API
Reading data from input elements
Data classes
Showing data to the user
Showing weather details
Named parameters
Extension functions
Giving final touches
Adding CSS
Interoperability with JavaScript
Summary
Chat Application with Server-Side JavaScript Generation
Creating our first Node.js app using Kotlin
Choosing an IDE
Installing Node.js
Installing the Node.js plugin
Creating a project
Creating a chat application
Setting up the Node.js server
Specifying the output files
Examining the compilation output
Specifying the router
Starting the node server
Creating a login page
Creating an index.ejs file
Using DSL
Using kotlinx.html
Lambda functions
Reading the nickname
Passing nickname to the server
Smart cast
Registering a callback
Establishing a socket connection
Setting up Socket.IO
Listening to events
Emitting the event
Incrementing and decrementing operator overloading
Showing a list of online users
Using the data class
Using the Pair class
Iterating list
Sending and receiving a message
Null safety
Force unwraps
Using the let function
Named parameter
Disconnecting a socket
Styling the page using CSS
Summary
News Feed – REST API
What is REST?
What is Ktor?
Why Ktor?
Understanding unopinionated applications
Asynchronous nature
Highly testable
Deploying the Ktor app
Let's build our news application
News provider
Fetching news sources
Fetching news articles
Preview
Features
Architecture
Setting up the IDE
Prerequisites
Creating the project
Project structure
Deploying
Deploying in IntelliJ IDEA
Setting up the build script
Adding Kotlin dependency
Adding Ktor dependencies
Configuring logging
Adding Fuel
What is Fuel?
Adding Gradle dependency
Quick sample
Asynchronous mode
Blocking mode
Completing Gradle script
Let's code!
Application configuration
Deployment block
Application block
Application main
Installing routing
Simple routing
Modular routing
Understanding route paths
Path parameters
Testing
Adding Gradle dependency
Testing the application
Testing the index URL
Testing JSON using Postman
Testing news sources using Postman
Testing news sources using Postman
Summary
CSV Reader in Kotlin Native
What is Kotlin Native?
Target platforms
Multiplatform Kotlin
Installing Kotlin Native
Installing from the source
Installing from binaries
Testing the installation
Memory management
Building our app
Writing the main function
Reading command-line arguments
Opening the file
Reading the file contents
Counting unique entries
Converting to Kotlin string
Splitting strings
Printing the result
Complete code
Running the program
Understanding the dataset
Compiling the program
Executing the program
Multiplatform Kotlin
Project structure
Common module
Platform module
Regular module
Overview of the dependency structure
Setting up a multiplatform project
Creating a multiplatform project with an IDE
Creating a multiplatform project without an IDE
Summary
Dictionary Desktop Application - TornadoFX
Introducing TornadoFX
Java-based desktop frameworks
TornadoFX special additions
Creating a type-safe UI versus FXML
Type-safe styling
Other improvements
Let's build our dictionary application
What we will build
Words API
Definition API
Features of our application
Setting up the IDE
Prerequisites
Installing the TornadoFX plugin
Creating the project
Project structure
Let's code!
Application class
Type-safe CSS
Dependency injection
Property delegate
Consuming the REST API
Defining the Model
Implementing the JSONModel interface
REST client
Configuring the client
Controllers
Views
Layouts
VBox layout
HBox layout
Other layouts
Forms
Background operations
Printing the result
Complete View
Launching the application
Summary
Kotlin is evolving rapidly as a universal language—a single language with which one can do many things and do it elegantly! It can be used to create a wide range of applications, spanning from large server applications that can take advantage of the most modern advances in parallel processing and rich internet applications (RIA) that run in the ecosystem of a web browser to Android apps and tiny applications that run within tiny IoT processors.
In May 2017, when Google announced official support to Kotlin to develop Android applications, the status of Kotlin was elevated overnight from a nice, cool language to a language that needs to be taken seriously. Shortly thereafter, the Spring framework, which is mighty on the server-side development, added Kotlin-only features. The Kotlin-favoring trend seems to have continued since then.
The vast array of applications that Kotlin can be used in and the value-add that Kotlin does in each of the cases with Kotlin-specific flavors can be quite overwhelming. This book is written to help the programmers find these in one place so as to put their hands around the diverse use case scenarios.
While there are books and plenty of online material covering the language basics, and then there are those covering single niche areas, there was nothing that could be referred to for understanding the vast spectrum of usage scenarios. This book tries to fill the void. This is a single book that can be used as a reference to these various scenarios.
This is not a theory book. It is a practical guide to creating industry-grade applications with Kotlin. Each chapter takes one moderately sized requirement in a given area and shows how to create a Kotlin application to fulfill it. It contains a complete set of instructions that a programmer can follow and learn the applications by coding them first hand. It also highlights the special uses of Kotlin features as they are applicable to the problem at hand.
Except for the first introductory chapter, all other chapters are independent of one another. You can, therefore, jump straight to the chapter corresponding to the application area that would be the most relevant for you, and dive deep into it to learn the skill quickly and put it to practice. It, thus, helps in accelerating your understanding and increasing the productivity in a short time.
We hope that the fast-growing community of Kotlin programmers will find this book immensely useful.
Chapter 1, The Power of Kotlin, is the introductory chapter. It covers why Kotlin is quickly becoming a force to reckon with. Kotlin positions itself as the smart choice to the various stakeholders, such as the programmer, the manager, and the businesses. The chapter looks at the technology and business reasons that fuel the adoption of Kotlin.
Chapter 2, Geospatial Messenger – Spring Boot, covers the use of Spring Boot technology to create robust server-side applications. Spring is one of the most well-known and well-respected server-side frameworks in the Java space, and Spring Boot is its less verbose and more powerful version. This chapter covers how a Geospatial Messenger application is created with Spring Boot technology using the Kotlin language.
Chapter 3, Social Media Aggregator Android App, is using Kotlin to create native Android apps. With Google officially recognizing Kotlin's use to develop Android apps, this is the most widespread application to use the Kotlin language. Today's mobile apps hardly work in isolation. They work with a server. This common scenario is illustrated with a social media aggregator app.
Chapter 4, Weather App Using Kotlin for JavaScript, explores the use of Kotlin to create rich internet apps that work within the browser. JavaScript is clearly the de facto standard language that works across all the browsers. However, Kotlin is clearly superior to JavaScript in many ways. This chapter shows how one can have the best of both worlds by doing the coding in Kotlin and, then, transpiling the code to JavaScript so that it works with the browsers seamlessly. The example that we will build is a simple weather application.
Chapter 5, Chat Application with Server-Side JavaScript Generation, explores how the same facility of transpiling Kotlin to Javascript can be used on the server side. JavaScript is used on the server side within the popular and fast Node.js framework. Kotlin can be used to create Node.js applications, as the JavaScript code that runs with Node.js can be generated from it. This chapter shows how to do so by creating a simple chat application.
Chapter 6, News Feed – REST API, covers the use of Kotlin specifically to create REST services. We will develop a News Feed application with the Ktor framework, which is a leading Kotlin-only framework used for server-side applications.
Chapter 7, CSV Reader in Kotlin Native, explores a bleeding edge technology—Kotlin Native—which is about compiling Kotlin code directly to platform-specific executables. Although not mature, Kotlin Native is worth watching as it quickly marches to its promise of becoming the only language to create native applications across disparate platforms such as iOS and Raspberry Pi. In this chapter, a small CSV reader utility is built with Kotlin/Native.
Chapter 8, Dictionary Desktop Application - Tornado FX, is about using Kotlin to create a cross-platform desktop application based on Java technology. Tornado FX is a Kotlin-specific framework, which is based on the most advanced Java GUI framework, that is, Java FX. This chapter illustrates the power of Tornado FX with a dictionary application.
You will need to have the following:
JDK8 (download it from
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
)
An IDE with the Kotlin plugin—you can use Eclipse (
http://www.eclipse.org
) and install the Kotlin plugin, or IntelliJ idea (
https://www.jetbrains.com/idea/download/
). The latter is more popular in the Kotlin community and is used in most of the chapters. The community edition is enough for most of the chapters, unless specified otherwise in the chapter.
Additional plugins may be needed to be installed into the IDE as specified in the respective chapter.
This practical guide is for programmers who are already familiar with Kotlin. If you are familiar with Kotlin and want to put your knowledge to work, then this is the book for you. Kotlin programming knowledge is a must.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://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 to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
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 macOS
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Kotlin-Blueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/KotlinBlueprints_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Our interest in the Kotlin programming language should be there because it is fast moving towards becoming the universal programming language. What is a universal programming language? From a simplistic view, the expectation could be that one language is used for all types of programming. While that may be far-fetched in today's complex world, the expectation could be adjusted to one language becoming the dominant programming language. Most certainly, it is the single, most important language to master. This book is written to help with that objective.
In this introductory chapter, we will see how Kotlin is poised to become the next universal programming language. In particular, we will look into the following topics:
Why can Kotlin be described as a
better Java
than any other language?
How does Kotlin address areas beyond the Java world?
What is Kotlin's winning strategy?
What does this all mean for a smart developer?
Historically, different languages have used strategies appropriate for those times to become the universal programming languages:
In the 1970s, C became the universal programming language. Prior to C, the programming languages of the world were divided between low-level and high-level languages, the former being the languages that were close to machine code and the latter being ones that were more concise and worked better for human understanding. The C programming language was developed as a single language that could work as a low-level and a high-level language. The Unix operating system was showcased as one that was built ground-up entirely in C, without needing another low-level language.
In the 1990s, Java became the universal programming language with the
Write Once Run Anywhere
strategy. Prior to Java, developers needed to create different programs to run on different platforms (different operating systems running on different hardware needed different programs to run). However, with Java, programs could be written targeting a single platform, namely the
Java Virtual Machine
(
JVM
). The JVM is available across all the popular platforms and takes care of all platform-specific nuances. The Java language became the universal language by being the language in which to write programs for the JVM.
Another two decades have passed, and the stage is all set to welcome the next universal language. Let's examine Kotlin's strategy to become that.
Why is being a better Java important for a language? For over a decade, Java has consistently been the world's most widely used programming language. Therefore, a language that gets crowned as being a better Java should automatically attract the attention of the world's single largest community of programmers: the Java programmers.
The TIOBE index is widely referred to as a gauge of the popularity of programming languages. Updated to August 2017, the index graph is reproduced in the following illustration:
The interesting point is that while Java has been the #1 programming language in the world for the last 15 years or so, it has been in a steady state of decline for many years now. Many new languages have kept coming, and existing ones have kept improving, chipping steadily into Java's developer base; however, none of them have managed to take the #1 position from Java so far.
