Book Image

Kotlin for Enterprise Applications using Java EE

By : Raghavendra Rao K
Book Image

Kotlin for Enterprise Applications using Java EE

By: Raghavendra Rao K

Overview of this book

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.
Table of Contents (13 chapters)

Introduction to Kotlin

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.

The history of Kotlin

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.

Features of Kotlin

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 imposes 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.

Getting started with Kotlin

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.

Installing Kotlin

Installing Kotlin on Linux

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

Installing Kotlin on Windows

To install Kotlin on Windows, perform the following steps:

  1. Extract and set the PATH variable to include the Kotlin runtime.
  2. Check its version using the kotlin -version command.
The source code for the Kotlin project can be found at the following link:
https://github.com/JetBrains/kotlin.

Installing Kotlin on Mac

To install Kotlin on a Mac system run the following command in a terminal:

$ sudo port install kotlin

Compiling and running

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 print 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