40,81 €
Build Java Enterprise Applications and learn how Kotlin makes it easier to code them using components like JSF 2.3, Enterprise JavaBeans (EJB) 3.2, Contexts and Dependency Injection (CDI) 2.0, the Java API for WebSockets, JAX-RS 2.1, Servlet 4.0.
Key Features
Book Description
Kotlin was developed with a view to solving programmers' difficulties and operational challenges. This book guides you in making Kotlin and Java EE work in unison to build enterprise-grade applications. Together, they can be used to create services of any size with just a few lines of code and let you focus on the business logic.
Kotlin for Enterprise Applications using Java EE begins with a brief tour of Kotlin and helps you understand what makes it a popular and reasonable choice of programming language for application development, followed by its incorporation in the Java EE platform. We will then learn how to build applications using the Java Persistence API (JPA) and Enterprise JavaBeans (EJB), as well as develop RESTful web services and MicroServices. As we work our way through the chapters, we'll use various performance improvement and monitoring tools for your application and see how they optimize real-world applications. At each step along the way, we will see how easy it is to develop enterprise applications in Kotlin. By the end of this book, we will have learned design patterns and how to implement them using Kotlin.
What you will learn
Who this book is for
Kotlin for Enterprise Applications using Java EE is for Java EE developers who want to build their enterprise project or application with Kotlin or migrate from Java to Kotlin. Basic knowledge of programming is necessary to understand the key concepts covered in this book.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 336
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing & Raghavendra Rao K
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 author, 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: Richa TripathiAcquisition Editor: Sandeep MishraContent Development Editor: Tiksha SarangTechnical Editor: Abhishek SharmaCopy Editor:Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Priyanka DhadkeGraphics: Jisha ChirayilProduction Coordinator: Shraddha Falebhai
First published: November 2018
Production reference: 1301118
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78899-727-0
www.packtpub.com
Despite the rapid proliferation of mobile and web technologies, developing software systems and applications for these environments continues to be complex and challenging. One of the primary reasons for this is the need to have an application run on an innumerable number of diverse devices and an increasing number of platforms. The fact that a programming language like Java is used in billions of devices today is due to its ability to work on any device regardless of its hardware and software, with the only requirement being the presence of the JVM interpreter. Modern and prominent programming languages, such as Kotlin, are taking the development of systems to the next level.
Kotlin is a language that has been designed from the ground up to be a modern language, and in the words of the founders, it is a pragmatic programming language for JVM and Android that combines OO and functional features focused on interoperability, safety, clarity and tooling support. You can use it for developing server-side applications, desktop applications, and mobile applications on Android, where it is also creating a significant buzz in the developer community. An impressive feature is the near-seamless interoperability with Java, with capabilities such as the ability to create mixed Java-Kotlin projects, as well as the ability to use Java libraries in Kotlin and vice versa.
In the healthcare industry, the product life cycle is quite long, and this means that interoperability with existing code and infrastructure is critical for us to be able to re-use existing assets while developing newer features based on modern programming concepts. Kotlin does a fantastic job on this front. Also, the flexibility to use native functional programming features in Kotlin while still being in the Java ecosystem is a huge plus.
Raghavendra, the author of this excellent book, has broad experience with programming languages. The fact that he has chosen to write his first book on Kotlin bears witness to his passion and enthusiasm for this language. The book brings out the inherent beauty of the language, but also states its limitations. This will certainly help the reader to get a balanced view and use Kotlin in their projects in the most appropriate way. It is well written and accessible, making it suitable for readers of any background.
Kotlin is here to stay, and we will certainly be hearing more of it in the coming years. This book will prove invaluable to those who want to embark on this exciting journey.
Henk van Houten
CTO Royal Philips
Raghavendra Rao K is a senior programmer who's skilled in Java, Kotlin, Groovy, Scala, Java EE, Spring Framework, Cloud Foundry, and Docker. He's a strong engineering professional with a bachelor of engineering degree focused on computer science and engineering. He's enthusiastic about code quality and loves refactoring.
Dr. Uri Benchetrit has, over 35 years, assumed a wide range of research and development positions in academia and industry in diverse fields, including software development, software architecture, algorithms, robotics, cellular phones, optics, and medical devices. Uri has been working for Philips since January 2010. He has served as the chief software architect for the CT/AMI Business Group at Philips, and then as the head of software engineering research and technologies in the Software Center of Excellence (SW CoE) of the Philips Strategy and Innovation office.
Uri holds a BSc in computer engineering, an MSc in data communications, and a DSc in robotics, all from the Technion. His post-doctorate research was done at the University of Michigan.
J Vijayananda has been in the IT industry for over 22 years. He has been primarily in the medical and healthcare domain. Vijay has been primarily focusing on machine learning and deep learning in the medical domain. Vijay is currently the chief architect and fellow at Philips Healthcare and leads the data science and AI platform at Philips.
He completed his bachelor's degree in electronics and communications from Mysore University, and also has a master's in computer science from Georgia Tech University.
Writing this book was only possible with the support of many individuals who gave generously their time and expertise. I have been fortunate to work with wonderful human beings on this journey.My sincere thanks to everyone who helped me with this projectwith their effort, knowledge, and the time they contributed to the book.
First and foremost I thank the platform development team of Kotlin at JetBrains, who put their thought and effort into creating a pragmatic programming language.
I express my sincere gratitude to technical reviewers of my book, Dr. Uri Benchetrit and J Vijayananda, for their time and support.
I had the privilege of Henk Van Houten writing the Foreword for the book. Thank you Henk for reviewing the book content and writing the Foreword.
My sincere thanks to Simao Williams, Dr. Eldo Issac, and Kenneth Kousen for the sharing feedback on the content of the chapters.
I also want to thank the wonderful team at Packt Publishing. Thank you Tiksha Sarang for editing the content very well. I also would like to thank Sandeep Mishra, Prajakta Naik, Abhishek Sharma, Riddesh Dawne and Storm Mann for their support in getting this book published.
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.
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 designed especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
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.packt.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.packt.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.
Title Page
Copyright and Credits
Kotlin for Enterprise Applications using Java EE
Dedication
Foreword
Contributors
About the author
About the reviewers
Acknowledgements
About Packt
Why subscribe?
Packt.com
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 in the book
Get in touch
Reviews
Kotlin – A First look
Technical requirements
Introduction to Kotlin
The history of Kotlin
Features of Kotlin
Getting started with Kotlin
Installing Kotlin
Installing Kotlin on Linux 
Installing Kotlin on Windows
Installing Kotlin on Mac
Compiling and running
A quick tour of Kotlin
Declaring variables
Data types in Kotlin
Warnings
Type inference
String templates
Multi-line String Literals
Expressions over statements
Functions
Default arguments
Named arguments
varargs and spread
The for loop
Iterating over a list
When clause
The nullable type
Lambda expressions in Kotlin
Extension functions
Classes in Kotlin
Constructors 
Static functions
Kotlin programming style and Syntax
Summary
Kotlin – The Game Changer
Technical requirements
Why Kotlin is the game changer
Interoperability with Java
Functional paradigms
Immutability
Null safety
Kotlin versus Java
Null safety issue
Arrays in Kotlin are invariant
Extension functions
No checked exceptions
Functional paradigms
Concise code
Configuring Kotlin in the project
Creating a simple Kotlin project
Maven project
Configuring Kotlin in Eclipse
Working with coroutines
Coroutines in Kotlin
Using Kotlin with Java
Kotlin in an existing Java project
Java in a Kotlin project
Summary
An Overview of Java EE and Kotlin
Technical requirements
Overview of Java EE
New features and enhancements in Java EE 8
Introduction to the Java EE architecture
Integrating Kotlin plugins
The all-open compiler plugin
Using the all-open plugin in Maven
Using the all-open plugin in Gradle
No-arg compiler plugin
Using the no-org plugin in Maven
Using the no-org plugin in Gradle
The kotlin-spring compiler plugin
Using the kotlin-spring plugin in Maven
Using the kotlin-spring plugin in Gradle
Using the kotlin-spring plugin in CLI
JPA plugin
Using the kotlin-jpa plugin in Maven
Using the kotlin-jpa plugin in Gradle
Using the kotlin-jpa plugin in CLI
The SAM-with-receiver compiler plugin
Using the SAM-with-receiver plugin in Maven
Using the SAM-with-receiver plugin in Gradle
Using the SAM-with-receiver plugin in CLI
The Jackson plugin
Using the Jackson plugin in Maven
Using the Jackson plugin in Gradle
Kotlin and Servlets
Kotlin for server-side development
Servlets
The life cycle of a servlet
Creating a simple servlet application
Kotlin and EJB
An overview of EJBs
Advantages of EJBs
The EJB component model
Bean validation
Summary
Kotlin with JSF and CDI
Technical requirements
Introduction to JSF
JSF architecture
The Benefits of using JSF
Developing our first JSF application
Kotlin and CDI
The Difference between EJB and CDI-managed beans
Injecting the beans
Producers
Qualifiers
Scopes
CDI and domain events
Defining an event
Listening to the event
Firing the event
Interceptors
Interceptor
Implementing the interceptor
Building custom interceptors
Defining a custom interceptor
Enhancing the auditable interceptor
Activating the interceptor
Summary
Kotlin with JPA and EJB
Technical requirements
Kotlin Data Classes
Java Persistence API
JPA architecture
Bootstrapping the JPA
Mapping domain entities using JPA
Queries
Modeling JPA entities
Mapping entities
OneToMany mapping
Cascading
Fetching strategy
Naming a join column
ManyToOne mapping
Data sources
Persistence units
Persistence context
Transactions
Exception handling
Using JPA in an application
Summary
Enterprise Messaging with Kotlin
Technical requirements
Understanding the messaging domains
Messaging architecture
Messaging domains
Point-to-point messaging model
Publish-subscribe messaging model
Messaging queues and topics
Java messaging System
Installing GlassFish
Configuring GlassFish
Building a messaging service using Kotlin
Point-to-point messaging
Writing a producer class
A quick comparison to Java code
Writing a Consumer class
Writing a test case for the Point-to-point messaging model
Publish-subscribe model
Writing a Publisher class
Writing a Subscriber class
Writing a test case for the publish-subscribe model
Message acknowledgement
Transactions
Enabling transactions in the point-to-point messaging model
Enabling transactions in the publish-subscribe messaging model
Summary
Developing RESTful Services with JAX-RS
Technical requirements
Web services
Working model of the web service
RESTful web services
Understanding REST verbs 
Resources
HTTP status codes
The 100 series
The 200 series
The 300 series
The 400 series
The 500 series
Introduction to JAX-RS
JAX-RS annotations
Implementing a RESTful service using Jersey
Implementing Real-World RESTful Web Services
Defining the layers
Writing a POST function for a create operation
Invoking the create organization API using cURL
Writing a GET function for a read operation 
Invoking the get organization API using cURL
Summary
Securing JAVA EE Applications with Kotlin
Technical requirements
Introduction to security API
The IdentityStore mechanism
EmbeddedIdentityStoreDefinition
DatabaseIdentityStoreDefinition
LdapIdentityStoreDefinition
HttpAuthenticationMechanism
BasicAuthenticationMechanismDefinition
FormAuthenticationMechanismDefinition
Custom form-based HTTP authentication
The SecurityContext API
Implementing security API using Kotlin
Securing JAX-RS APIs with JWT
The structure of JWT
Header
Payload
Signature
Implementing JWT
Summary
Implementing Microservices with Kotlin
Technical requirements
Introduction to microservices
Advantages of microservices
Breaking the monolith into microservices
Microservices architecture (MSA)
Developing real-world microservices
Developing the microservices
Developing the authentication service
Implementing the /authorize/jwt/token API 
Implementing the /authorize/jwt/verify-token API 
Developing the identity service
The flow diagram
Exception handling
Writing test code for microservices
Unit testing
Writing the skeleton for the test class
Setting up the test data
Mocking the response
Writing the assertions
Integration testing
Writing a REST client for the POST /authorize/jwt/token API
Writing a REST client for the /identity/organization/{orgId} API
Writing the assertions
Refactoring the integration test cases
Summary
Performance Monitoring and Logging
Technical requirements
Finding Memory Leaks
Application monitoring 
Java Mission Control
Java VisualVM
Garbage collection
Memory model
Types of garbage collector
Serial and parallel collectors
Concurrent collectors
Tuning the GC
High throughput and low latency
High throughput and low footprint
Low pause time and small footprint
Profiling
Profiling with JProfiler
Offline profiling
Getting our real-world application production-ready
Summary
Design Patterns with Kotlin
Technical requirements
Design patterns
Advantages of design patterns
Categorizing design patterns
Creational patterns
Structural patterns
Behavioral patterns
Implementing the singleton pattern
Writing a singleton class in Java
Writing the test case for a singleton
Lazy initialization
Singleton implementation in comparison to Kotlin
Implementing the factory pattern
Implementing the builder pattern
Implementing the decorator pattern
Writing the code for the decorator pattern
Adding decorators
Implementing the observer pattern
Illustrating the observer pattern
Implementing the chain of responsibility pattern
Illustrating the chain-of-responsibility pattern
Defining the contracts
Writing the implementation
Defining the concrete handlers
Verifying the handler implementation
Selecting design patterns
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
It is always exciting to embark on a new journey, and learning a language is no different. This process is a fun-filled journey that brings with it the true satisfaction of learning. In the process of developing the software or an application, choosing a programming language has always been a topic for debate. Several JVM-based programming languages have been available for application development, such as Java, Groovy, and Scala. When there are so many languages around, why do we need another one? Well, the answer is that any language is conceptualized for a specific task and audience. Typically, the language gets richer over a period of time as a result of the developer community. But one language typically will not have all the features required. Kotlin combines several nice features that are there in different languages. Its elegant syntax and the non-verbosity of the code makes application development faster and efficient to manage.
Kotlin combines the features of the object-oriented and functional style of programming to choose from, based on the context suitable for enterprise application development. Kotlin is developed with the intention of making the programming experience easier and solving the problems that programmers face while developing and maintaining an application or a microservice. This adds to the value proposition in an application's life cycle by saving time and keeping it productive while developing the solution. Kotlin is a very pragmatic language that caters well to the needs of enterprise applications. Kotlin aids application development by having a lot less code compared to any other JVM-based languages, which essentially means that developing the application would become faster and maintenance easier. Language is non-verbose and hence, it is less error-prone. Elegance in syntax improves the readability of the code. Kotlin is a statically-typed language, so type safety is guaranteed.
For all these reasons, Kotlin is a great fit for enterprise application development.
Thank you for selecting this book. I hope you will enjoy reading it and apply the learnings to developing enterprise systems.
This book is designed for programmers, application developers, architects, and technical managers. It assumes a degree of familiarity with the fundamentals of the programming and basics of Java and JDK in general, but does not assume any knowledge of the Kotlin language.
For application developers and architects, this book covers the various aspects of developing enterprise applications. It covers the fundamentals of the Kotlin language required to get started with this book and goes on to discuss various aspects for developing enterprise applications. The book can be used as a reference guide for developing enterprise applications using Kotlin and Java EE, with elegant and expressive syntax that the Kotlin language offers.
The book starts with the fundamentals of Kotlin language and a brief about Java EE platform, then focuses on using Java EE with Kotlin. It also covers RESTful services, securing services and implementing Microservices. Lastly it covers Application monitoring, Profiling and Design Patterns.
Chapter 1, Kotlin – a First look, we’ll be introducing you to the world of Kotlin. We learn the basics of Kotlin and take a quick dive into various features that the Kotlin language offers.
Chapter 2, Kotlin – The Game Changer, explains how Kotlin would be a game changer in terms of developing real-world, enterprise applications. We discuss where Kotlin scores over Java and why it is becoming increasingly popular. After addressing key practices, and the advantages it has, we'll be building a basic Kotlin project using IntelliJ IDEA and Eclipse. We then cover the Coroutines (a very lightweight thread) used for programming asynchronously. We will also learn about intermixing Java and Kotlin.
Chapter 3, An Overview of Java EE and Kotlin, gives a bird's eye view of the Java EE platform. We'll be introducing Kotlin in our Java EE applications. We discuss the challenges that Java EE needs to tackle to make Kotlin work in unison. The Kotlin plugins that will aid in the cause will be integrated into our Java EE applications as we begin our journey to build apps using Kotlin and embrace the new programming language. We also cover creating a web application using Servlets, and EJB with Kotlin.
As Kotlin is based on JVM, it is fully compatible with existing Java-based frameworks such as JSF.
Chapter 4, Kotlin with JSF and CDI, discusses how to make Kotlin work with JSF and dependency injection using CDI. We then discuss how we can use CDI to create domain events. We also cover interceptors and a use case where they can be applied. This chapter will be another significant step in our journey of developing Java EE applications using Kotlin.
Chapter 5, Kotlin with JPA and EJB, explains how to bootstrap JPA with Kotlin. We then move onto modeling JPA entities. We also discuss transaction management and handling exceptions in an application. Along the way, we'll integrate each of the preceding frameworks to build a real-world application.
Java EE 8 introduced JMS 2.0, which greatly simplified the development of applications involving messaging functionality.
Chapter 6, Enterprise Messaging with Kotlin, covers the development of messaging models using Kotlin and the Java Messaging Service (JMS). We will discuss messaging queues and topics. We will implement Point-to-point and Publish-Subscribe messaging models. We will also cover the acknowledging of messages and transactions.
Chapter 7, Developing RESTful Services with JAX-RS, discusses the concepts of REST specifications and examples of JAX-RS API. Furthermore, we'll be looking at Jersey—a popular implementation of JAX-RS API, while implementing them in web services using Kotlin.
Java EE 8 introduces a new security API that standardizes application security across all Java EE 8-compliant application servers. The new Java EE 8 API includes support for authentication mechanisms, allowing us to authenticate users in a standard way. Several authentication mechanisms are supported, such as basic HTTP authentication, client certificates, HTML forms, and more. We will discuss what the Security API is all about, along with developing a web application that implements the same using Kotlin in chapter 8.
Chapter 8, Securing Java EE Applications with Kotlin. It also covers implementation of the JSON Web Token (JWT) to secure the RESTful APIs.
The main purpose of a microservice architecture is to break down an application into smaller standalone components that are easier to handle, deploy, scale, and maintain in the long term.
Chapter 9, Implementing Microservices with Kotlin, examines ways to refactor monolith applications into microservices. We will implement microservices using Kotlin.
Chapter 10, Performance Monitoring and Logging, discusses how to find memory leaks. We'll be exploring the performance and monitoring tools used for enterprise applications. We'll look into garbage collection (GC), tuning the GC, and profiling.
Design patterns may be viewed as a structured approach to computer programming. A software design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
Chapter 11, Design Patterns with Kotlin, dives into the various design patterns. We will learn the different types of patterns, specifically among the creational, structural, and behavioral patterns, and implement them using Kotlin.
To run examples from this book, you will need a computer running Windows, Linux, or macOS. You will also need IntelliJ IDEA (preferably IntelliJ Ultimate edition) or Eclipse. You will need a basic knowledge of GitHub and Git to clone project samples discussed in the book.
To run examples and programs covered in the book requires Kotlin 1.3 and Java 1.6 or higher. Most of the examples will also work with the earlier version of the Kotlin. The instructions to download necessary software and tools are provided in technical requirements of the each chapter.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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.packt.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 GitHub at https://github.com/PacktPublishing/Kotlin-for-Enterprise-Applications-using-Java-EE. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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: "We will create a message Producer class."
A block of code is set as follows:
class Producer {
@Inject
private lateinit var
initialContext
: InitialContext}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
class Producer {
@Inject
private lateinit var
initialContext
: InitialContext
}
Any command-line input or output is written as follows:
> kotlinc -script 14c_SecondaryConstructor.kts
Bold: Indicates a new term, an important word, or words that you see on screen. For example: "The Java Messaging System (JMS) is the standard API for messaging systems."
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.
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 packt.com.
Kotlin is a new language based on the Java Virtual Machine (JVM) that is fascinating the developer community with its concise, clear syntax, its lack of boilerplate code, and its full interoperability with the Java language.
The following topics will be covered in this chapter:
The features offered by Kotlin
Installing and running Kotlin
The various constructs of the language
Knowing the basics of the Java language will help you to understand Kotlin and compare the two JVM-based languages. We will work with the command line to illustrate the language features that are highlighted in this chapter.
Kotlin is a statically-typed programming language that runs on the JVM and works across different platforms. The fact that it is statically typed means the types are resolved during compilation. JVM is a specification that provides a runtime environment for running applications that are developed in Java and other JVM-based languages. The most well known reference implementation of JVM is OpenJDK, which was originally developed by Sun Microsystems and is now supervised by Oracle. Kotlin is another JVM-based language that is simple to write and concise in nature.
Kotlin combines object-oriented and functional programming features. Kotlin is designed to be interoperable with Java and relies on the Java code from the existing Java Class Library (JCL).
Kotlin provides a more expressive syntax than Java. It is concise and has strong type inference, which reduces code verbosity. It also has a wide variety of useful features, such as operator overloading, string templates, extended functions, and coroutines.
Kotlin was developed by JetBrains in 2010. They initially released it under the name Project Kotlin in July 2011. They needed a language that was concise, elegant, expressive, and also interoperable with Java, as most of their products were developed in Java, including the Intellij Idea. They were looking for an alternate language to reduce the amount of boilerplate code required and to introduce new constructs, such as higher-order functions, to make language more expressive and concise. One of the goals of the Kotlin language was to be able to compile code as quickly as Java.
JetBrains open-sourced the project under the Apache 2 license in February 2012. Kotlin v1.0 was released on February 15, 2016. This was the first official stable release from JetBrains. Kotlin v1.2 was released on November 28, 2017. This release added a feature to allow code to be shared between JVM and JavaScript platforms.
The key features of Kotlin are as follows:
Interoperability with Java
: The most important feature of Kotlin is its deep interoperability with Java. Kotlin compiles to JVM bytecode and runs on the JVM, using Java libraries and tools.
Concise
: Unlike Java, which is verbose, Kotlin reduces the amount of boilerplate code. This results in a leaner code syntax and improved readability.
Safe
: Kotlin improves code safety through the proper initialization of properties, null safety, and strong type inference.
No runtime overhead
: Kotlin i
mposes no runtime overhead. The standard Kotlin library is small. The Kotlin runtime exists only to support the language features.
It has
mostly focused on extensions to the Java standard library.
Many of its internal functions are inline.
Collections
: In Kotlin, we have higher-order functions, lambda expressions, operator overloading, lazy evaluation, and lots of other useful functions for working with collections.
Extension functions
: Kotlin allows us to extend the functionality of existing classes without inheriting from them. Extensions do not modify classes; they extend them and are resolved statically.
Open source
: Kotlin is an open-source programming language. The Kotlin project is open-sourced under the Apache 2.0 license. It is on GitHub and is open for community contribution.
Before installing Kotlin, we need to have JDK installed, as Kotlin relies on JDK.
In this course, we will be using OpenJDK. OpenJDK can be downloaded from http://jdk.java.net/. Alternatively, we can use Oracle JDK, which can be downloaded from http://www.oracle.com/technetwork/java/javase/downloads/index.html.
After installing the JDK, set the PATH variable to include the JDK installed and we can check its version using the java --version command.
Once we have JDK installed, we need to set up Kotlin. We will look at how to install it in the following section.
Kotlin can be downloaded using the following link: https://github.com/JetBrains/kotlin/releases.
To install Kotlin on Unix based systems such as Linux, Solaris, OS X etc., run the following commands in a terminal.
$ curl -s https://get.sdkman.io | bash
Then open a new terminal and execute below commands to install Kotlin:
$ sdk install kotlin
We can run the following command to see the version of Kotlin:
$ kotlin -version
To install Kotlin on Ubuntu, execute the following command from a terminal:
$ sudo snap install --classic kotlin
To install Kotlin on Windows, perform the following steps:
Extract and set the
PATH
variable to include the Kotlin runtime.
Check its version using the
kotlin -version
command.
To install Kotlin on a Mac system run the following command in a terminal:
$ sudo port install kotlin
Now that we have JDK and the Kotlin compiler set up, let's try writing our first program in Kotlin and learn a few different ways to compile and run it.
Let's consider the HelloWorld.kt program, which just prints the hello message and the first argument passed to it:
fun main(args:Array<String>){ println("Hello${args[0]}")}
There are different ways to compile and run Kotlin code:
Command line
: By including the runtime, we don't have to provide the classpath; it gets bundled into it. To bundle the JAR, execute the following command in the command prompt/console:
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
We pass the class name and include the runtime and the name of the JAR as command-line arguments.
In order to run the program, execute the following command:
kotlin -classpath helloworld.jar HelloWorldKt World
Alternatively, we can use the following command:
java -classpath helloworld.jar HelloWorldKt World
The output is as follows:
We can also compile Kotlin code without the runtime. When we want to run it using Java or Kotlin, we have to specify where the class file,HelloWorldKt, is located:
kotlinc HelloWorld.kt -d classes
kotlin -classpath classes HelloWorldKt World
The output is as follows:
Read-eval-print-loop
: Kotlin has an
read-eval-print-loop
(
REPL
) that we can use. Simply type
kotlinc
in the terminal
and it will become an REPL.
We can now run the Kotlin code interactively and experiment with it, as demonstrated in the following:
We can type :quit to exit the REPL.
Scripts
: We can create a script file to compile and run a Kotlin program. Create a file called
HelloWorld.kts
. The
s
in the file extension stands for
script
. Then add the following
statement to it:
println("Hello World from Script")
HelloWorld.kts just has one print line statement. In the console, execute the following command:
kotlinc -script HelloWorld.kts
This gives the output shown in the following screenshot:
This way, we can directly run the Kotlin file as a script.
In this section, we have learned the following:
How to install Kotlin
How to compile and create byte code and run it
How to code and play with REPLs directly
How to write Kotlin code as a script and run it
In this section, let's take a quick look at the world of Kotlin and understand the basics of the language.
If we have created a variable and not used it, or if we forget to initialize a variable, we will get warnings, which can be useful to prevent errors. Kotlin provides many such warnings during compile time to avoid possible runtime errors. This increases program reliability.
