Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kotlin for Enterprise Applications using Java EE

You're reading from   Kotlin for Enterprise Applications using Java EE Develop, test, and troubleshoot enterprise applications and microservices with Kotlin and Java EE

Arrow left icon
Product type Paperback
Published in Nov 2018
Publisher Packt
ISBN-13 9781788997270
Length 388 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Raghavendra Rao K Raghavendra Rao K
Author Profile Icon Raghavendra Rao K
Raghavendra Rao K
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Kotlin – A First look FREE CHAPTER 2. Kotlin – The Game Changer 3. An Overview of Java EE and Kotlin 4. Kotlin with JSF and CDI 5. Kotlin with JPA and EJB 6. Enterprise Messaging with Kotlin 7. Developing RESTful Services with JAX-RS 8. Securing JAVA EE Applications with Kotlin 9. Implementing Microservices with Kotlin 10. Performance Monitoring and Logging 11. Design Patterns with Kotlin 12. Other Books You May Enjoy

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
You have been reading a chapter from
Kotlin for Enterprise Applications using Java EE
Published in: Nov 2018
Publisher: Packt
ISBN-13: 9781788997270
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image