Kotlin— The Game Changer!

KonfHub
9 min readJan 25, 2019

Written by Raghavendra K. Rao

Enterprises typically have developed the application, microservices based on Java programming language. Java is first choice of language for the development, because its robust, safe, backward compatible. Java’s platform independence makes it suitable for developing web services and global enterprise applications.

Having said that Java is the first choice of programming language for application development and is so integrated in our work life, but have we ever thought is there a better way to write code which eases the development.

In recent years different JVM based languages like Scala, Groovy are also made an attempt to simplify the programming. Now there is a new JVM language which is making developer community excited with its cool features. Kotlin is relatively new language that we are talking about.

We will discuss how Kotlin making sound with its features and why it is a game changer in the application development world.

Kotlin is a statically typed programming language that runs on JVM (Java Virtual Machine). Kotlin combines the features of object-oriented and functional programming. It is develop by JetBrains.

History of the Language

In July 2011 JetBrains released the ‘Project Kotlin’, a new language for the JVM, which had been under development for a year. JetBrains said that most languages did not offer the features that they were looking for, except Scala which had slow compile time. One of the goals of the Kotlin is to compile the code as quickly as Java.

In February, JetBrains open sources the project under the Apache 2 license.

Kotlin v1.0 was released on February 15, 2016. This version is considered to be the first officially stable release from JetBrains and it has committed to long-term backwards compatibility starting with this version. Kotlin v1.2 was released on November 28, 2017. Sharing Code between JVM and JavaScript platforms feature was newly added in this release.The latest stable version is Kotlin v1.2.61, which released in Aug 2018.

Features that Kotlin offers

Kotlin is developed with the intent of adding features which is not found in existing JVM languages, directly addressing the challenges of the Java and other JVM languages. Kotlin is seamlessly interoperable with Java, ensuring the existing applications or services face no issues. Kotlin is a modern JVM language with 100% Java interoperability. Kotlin has all the features of modern languages to offer. Kotlin has a Null safety, functional style of coding, non-verbose code, a clean and easy to use Stream operators (filter, map, reduce…), to improve your development life cycle and productivity.

Interoperability with Java

One of the main reasons for Kotlin’s wide acceptance from the developer community is that its cent percent interoperable with Java. It never changed any of the existing Java functionality. That means if we are in the middle of an application or micro service written in Java, we can use Kotlin and leverage its new features.

If we have an existing Java project and want to leverage the advantage that Kotlin offers, we can do this. We can add new code in Kotlin to an existing Java project or you can convert the Java code to Kotlin. In an application, part of the code can be written in Java and some part written in Kotlin and it just works seamlessly together.

Let’s look at an example where we add Kotlin code to an existing Java project created using maven. For example, we have created a simple maven project that has some code written in Java, which is shown below.

Let’s add Kotlin code to it.

1) Right click on the src/main/java | new Kotlin File/Class.

2) After creating a Kotlin file IDEA prompts for us to configure the Kotlin runtime.

3) Click on configure, choose maven.

4) Choose the desired Kotlin version and hit OK button.

Now we have configured the Kotlin runtime in a Java project.

5) The App.java and NewApp.kt files are hello world class which just prints hello world message to the console.

App.java

public class App {
public static void main (String[] args) {
System.out.println ("Hello World from Java!");
}
}

NewApp.kt

object NewApp {
@JvmStatic
fun main(args: Array<String>) {
println("Hello World from Kotlin!")
}
}

We can also write main function without the class structure as follows. It just compiles and runs.

fun main(vararg args: String) {    println("Hello World from Kotlin!")
}

Also note the input args to the main() function, we can use vararg followed by the argument name and the type.

Let’s run the both Java and Kotlin code.

Output from Java code:

Output from Kotlin code:

As we can see, both Kotlin and Java can exist in a same project and also we can load and use any Java class or a library written in Java from a Kotlin class.

Functional paradigm

Kotlin supports functional style of programming and allows us to write more elegant, concise and expressive code.

In Kotlin we don’t have to write lengthy code for simple functionality. Pure functions and higher order functions avoids mutating the states and reduces the code complexity, thus improves the readability of the code.

Lambda expression is a anonymous function which represents the implementation of single abstract method of an interface (known as SAM interface). Lambda expressions can be passed around the function which turns a function to be higher order function.

Let’s write a lambda expression. Consider the following lambda expression,

val greetingLambda = { println("Greet from inline lambda") }

This can be invoked using,

greetingLambda() or
greetingLambda.invoke()

Output:

We will write an inline lambda expression to print even numbers.

listOf(0,1,2,3,4,5,6,7,8,9).filter{ e -> e % 2 == 0}.forEach{ e -> println(e)}

Output:

Immutability

Immutability is opposite of mutation. Mutation is where we modify state of an object. Mutation is error prone and makes debugging difficult. Kotlin enforces immutability by with its val keyword and in its collections, which are immutable by default. Once the val or a collection is initialized, we can be sure about its validity. Immutability makes it easier to write, use and reason about the code. The internal state of application will be more consistent.

Let’s consider below code sample.

object ImmutabilityTest {
@JvmStatic
fun main(args: Array<String>) {
val msg = "Hello"
msg = "hi"
println(msg)
}
}

If we compile this code, it gives compilation error that the value for msg cannot be changed.

[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to C:\Drive\MyWorks\Kotlin\projects\Intermixing Java and Kotlin\myJavaApp\target\classes
[INFO]
[INFO] --- kotlin-maven-plugin:1.2.41:compile (compile) @ myJavaApp ---
[ERROR] C:\Drive\MyWorks\Kotlin\projects\Intermixing Java and Kotlin\myJavaApp\src\main\java\ImmutabilityTest.kt: (11, 9) Val cannot be reassigned
[INFO] ------------------------------------------------------------------------

Null-safety

When we wrote code where we declare the fields in a class. We were not sure whether the field is initialized or not. We used null checks and @Nullable, @NotNull annotations helped in some context. Now, in Kotlin, we precisely know what field can be null, what fields are initialized and get strict control over the fields.

Consider following code,

object NullabilityTest {
@JvmStatic
fun main(args: Array<String>) {
var msg: String = null
println(msg)
}
}

Let’s compile this code.

[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.2.41:compile (compile) on project myJavaApp: Compilation failure
[ERROR] C:\Drive\MyWorks\Kotlin\projects\Intermixing Java and Kotlin\myJavaApp\src\main\java\NullabilityTest.kt:[10,28] Null cannot be a value of a non-null type String

This code gives compilation error.

If we want to assign a null value to a variable, it has to be declared like,

var msg: String ?= null

Now the variable ‘msg’ be declared with a null value.

Let’s consider another example.

object NullabilityTest {
@JvmStatic
fun main(args: Array<String>) {
var userList:ArrayList<String> ? = nullprintln(userList.get(0))
}
}

Variables declare to hold null value. If we invoke any function on these variable, say userList.get(0), it doesn’t throw NullPointerException at runtime instead it fails to compile only. Kotlin catches possible NullPointers during the code compilation time itself. It warns us to initialize the var before accessing it. No null pointer issues post deployment of the application. Hence almost no NullPointerException.

Error:(6, 25) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type kotlin.collections.ArrayList<String>? /* = java.util.ArrayList<String>? */

Since the variables is declared to hold null value, we need to perform null check before accessing any function on this variable.

Kotlin provides an elegant syntax for null check. ?. is used for null check.

userList?.get(0)

Kotlin provides an elegant syntax to safely perform an operation on the var that can hold null values. Consider the below code.

fun main(args: Array<String>) {
var userList:ArrayList<String> ? = nullvar user = userList?.get(0)
user ?.let {
println("got the user details")
} ?: run {
println("there is no user")
}
}

Here we create list of users, userList and try to get first object and do something on that. In this case, user is null and when we use ?. on it it doesn’t throw Null Pointer Exception. It checks if the ‘user’ is not null it prints ‘got the user details’ message to the console. If it is null, it prints ‘there is no user’ message.

Testing

We can also write test cases in Kotlin. We can write Junit tests, integration tests easily in Kotlin.

Consider the below class, which has a function called hello() that returns a String message.

class HelloWorld {
fun hello(): String {
return "hello"
}
}

Let’s write a unit test case for this class. We use mockito for mocking our HelloWorld class.

class HelloWorldTest {    internal var helloWorld = mock(HelloWorld::class.java)    @Test
fun testHello() {
val mockMessage = "hello"
`when`(helloWorld.hello()).thenReturn(mockMessage)
val message = helloWorld.hello() Assert.assertNotNull(message)
Assert.assertEquals("hello", message)
}
}

We mock the response when the function hello() is invoked and return the mock response. We assert for the message and the content.

In short, choosing language for application development is a choice. If we already have a application written in Java, we can include Kotlin to get benefit that it offers. Once the code is compiled, all is bytecode, no distinction whether which one written in Java or Kotlin. As Kotlin is interoperable with Java and provides elegant way of writing code that reduces development life cycle and is less error prone. Kotlin is feature packed language and writing code become much simpler and concise. We can develop the applications quickly and easily and maintenance become a lot easier with it.

Kotlin for Enterprise Applications using Java EE

If you found this article interesting and want to learn more about Kotlin, you must check out Kotlin for Enterprise Applications using Java EE. Since Kotlin offers more benefit in terms of reducing boilerplate code, friendly syntax, it’s a great fit for developing enterprise applications. Kotlin for Enterprise Applications using Java EE is a must-read for Java EE developers who want to build their enterprise project or application with Kotlin or migrate from Java to Kotlin.

This article was written by Raghavendra K Rao and published with permission from Packt Publishing.

--

--

KonfHub

KonfHub is the one-stop platform to create and host tech events. Create the event in under 30 seconds, gamify & amplify for audience engagement!