What Are Some of the Differences Between Kotlin and Java?

Niall Richards
Version 1
Published in
8 min readFeb 13, 2023
Photo by Louis Tsai from Unsplash

In the run up to Christmas, several of us at Version 1 were given the opportunity to learn more about the Kotlin programming language. This consisted of attempting the Kotlin Koans online course for the first couple of days, followed by another couple of days with Elena van Engelen-Maslova (an external trainer with knowledge of Kotlin). In the latter of which, we did some more Kotlin exercises and had the opportunity to create an AWS stack with Kotlin as its main programming language.

During the week it became apparent that Kotlin and Java, despite both being JVM languages, have several substantial differences.

What is Kotlin?

Kotlin is an open-source programming language that can run on Java Virtual Machine (JVM). As a result of this, much like Java, the language can run on numerous platforms.

It is a language that combines Object Oriented Programming (OOPs) and functional programming in an unrestricted, self-sufficient and distinctive platform.

What is Java?

Java is a multi-platform, object-oriented, and network-centric programming language. It is among the most used programming language. It also used as a computing platform, and it was first released by Sun Microsystem in 1995. It was later acquired by Oracle Corporation.

Features of Kotlin:

• Less use of boiler plate code than Java

• Kotlin utilizes JVM

· Supports functional and object orientated

• Kotlin can support a variety of extension functions without making any changes to the code

• You can write Kotlin code using IntelliJ by default, other IDEs using plugins (such as the “Kotlin Plugin for Eclipse”) or using the command-line interface

• Smart feature casting helps you to cut down the application costs and improves its speed or performance

We decided to use Intellij IDEA IDE by Jetbrains. This is an incredibly versatile platform used mainly for importing, developing, and deploying computer software. There is a community and ultimate version available, but for the purpose of practicing Kotlin code, the community version is more than enough. This also offers a free Kotlin course “Koans” to assist with learning.

Null safety built in

Kotlin has built-in null safety. This will help developers avoid null reference exceptions, which can be a common source of bugs in Java. In Kotlin, properties and variables can be marked as nullable. Null checks can then be performed using the ? operator. This will help to prevent null reference exceptions at compile-time, rather than at runtime.

An example of Kotlin code below:

fun calculateSum(a: Int, b: Int) = a + b

val x: Int = calculateSum(1, 2)
val y: Int? = null
val z: Int = y

The code above shows the variables ‘x’ and ‘z’ are non-nullable, while ‘y’ is nullable. The assignment ‘val z: Int = y’ won’t compile, because ‘y’ is nullable and the ‘z’ is non-nullable. This will help to prevent null reference exceptions from occurring at runtime.

You can use the safe call operator (‘?’) to access the value of nullable variable. This operator allows you to safely access the value of a nullable variable without the risk of a null reference exception.

An example below:

val y: Int? = null
val result = y?.let {
// Do something with y
}

The ‘let’ function will only be called if the ‘y’ is non-null. If ‘y’ is null, the ‘result’ variable will be assigned a null value. This will allow you to safely access the value of a nullable variable without risk of a null reference exception.

In conclusion, Kotlins’ built-in null safety features will help developers to write more reliable and safer code, and also help to reduce the occurrence of null reference exceptions in Kotlin applications.

Syntax

While Java and Kotlin have many similarities, there are also some notable differences in their features and syntax. A few examples of the differences are shown below.

Null Safety: There is built-in null safety for Kotlin. This means that it is not possible to return or assign null values from variables, unless they are explicitly marked as nullable. This will help to prevent common null pointer exceptions with Kotlin. The !! operator can be used to assert that an expression is non-null.

String Templates: Kotlin has a more concise syntax for string templates. This allows you to embed expressions and variables directly in a string literal. The ‘$’ character can be used, then followed by an expression or variable, to include its value in a string. When accessing a property however, the value must be in curly braces. E.g. Hello ${foo.bar}

Variable Declarations: In Kotlin, variable types can be inferred from the value being assigned, while in Java, variables must be declared with specific type.

An example of Java below:

int x = 10;

An example of Kotlin below:

val x = 10

Note: As of Java 10 you can use the var keyword so that you do not have to specify the type of the variable. However, this can only be used for local variables.

Lambda Expressions: For Lambda expressions, Kotlin has improved support, which are anonymous functions that can be passed as arguments to other functions. Kotlin expressions are denoted by the ‘{ }’ characters, their return type and parameters are inferred from the context they are used in.

Extension Functions: Kotlin will allow you to define extension functions. These are functions that can be called on an object of a particular type. This will add additional functionality to existing types without having to modify their code.

Kotlin JVM, Kotlin for JavaScript, and Kotlin Native

Kotlin is a cross-platform language that can be used to applications for multiple different platforms, including Java Virtual Machine (JVM), JavaScript, and native platforms, which makes it a versatile language that can be used for a wide range of development projects.

Kotlin has access to the full set of Java libraries and frameworks when running on the JVM, as well as third-party libraries and frameworks that are designed to work with Java. This in turn makes it easy to build applications that integrate with existing Java-based systems, allowing you to make use of the many libraries and tools available for the JVM.

When Kotlin is compiled to JavaScript, it can be used to build web applications and other types of applications that will run in a browser.

When Kotlin is run natively, it can be used to build applications that are compiled directly to native code and run on the host operating system which is very useful for building high-performance applications that are run directly on the hardware.

Functions can exist outside a class in Kotlin

Unlike Java, in Kotlin it is possible to have functions declared outside of classes. This is especially useful for replacing final classes which help with utility functions, which may need to be used across multiple other classes. For example, in Java if you wanted to have a function that could be accessed everywhere, you would have to have something like this:

public final class HelperUtils {
public static String helperString(String str){
String returnString;
// Do something
return returnString;
}
}

In contrast, in Kotlin this method would not require an outer class and could like this:

fun helperString(str:String): String() {
var returnString
// Do something
return returnString
}

This saves on the amount of code required and aids readability.

Extension functions

Functions can be added to add functionality to an object or primitive type without having to inherit from the class or add the method to the class itself. You could also use it to add new functions for libraries you are using, which you can’t modify yourself. However, it is best to avoid extending things which are too generic as these could cause issues early on. For example, it would be a bad idea to extend the generic Object class as then your method could apply to everything which derives from that. Which most likely, is not what you want. An example of an extension function is given below:

fun List<Unicorn>.filterBySize(sizeFrom: Int): List<Unicorn> = this.filter { it.size == sizeFrom }

The above example is from one of the exercises in the Kotlin course mentioned (From “Unicorn Challenge” by Elena van Engelen). The above code takes a list of unicorn objects and sorts them by their size.

Classes are final by default in Kotlin

Unlike Java where classes are open by default, in Kotlin they are final. If you wish a class to be Open in Kotlin you must use the open keyword. An example is given below:

open class Customer

There are plugins which change this however, so that classes are open by default such as the All-open compiler plugin.

Nothing Return Type

Useful for methods which will always throw an Exception. An example is given below:

fun failWithWrongAge(age: Int?): Nothing {
throw IllegalArgumentException("Customer bust be at least 16 for a bank account. Age was $age")
}

No Checked Exceptions

One of the biggest differences that Kotlin has compared with Java is its lack of checked exceptions. The idea of this is to encourage developers to handle exceptions in the correct place. For example, in Java a class may throw an exception further down in the stack which either is logged or rethrown in the best-case scenario (in some pieces of Java code there isn’t anything in the catch block, which of course is not Java best practice). However, since there are unchecked exceptions, you will need to deal with these at the appropriate level in your code.

No semi-colons required

Not much else to say here really. Kotlin does not enforce or require semi-colons at the end of each line.

Summary

To sum up, Kotlin has several changes which help make it a better language in some areas than Java is. It is also clear that Kotlin is gaining in popularity due to Google adopting it for the development of Android applications and other companies adopting it for the development of web applications. Of course, we are aware that the software development community is known for its strong opinions on such things, so what do you think of Kotlin? Is it a Java killer? Or will it only replace Java in certain situations?

Note: The above is not a comprehensive list of all the differences between Kotlin and Java. However, they are the ones which were most apparent when we were doing our Kotlin course or were pointed out to us. For a more comprehensive list, see the Kotlin documentation which has been linked to below.

Useful Links and Extra Reading

Kotlin Docs | Kotlin Documentation (kotlinlang.org)

On Kotlin | Baeldung on Kotlin

Everything you Need to Know About IntelliJ IDEA IDE | Edureka

What is Kotlin? — A Beginners Guide to Kotlin Programming | Edurek

About the Authors

Rhys Beazley (Associate Consultant), Greg Bell (Associate Consultant), and Niall Richards (Senior Java Developer) work here at Version 1.

--

--