Why I switched from Java to Kotlin

Kotlin is a cross-platform, general-purpose programming language and an easy move for anyone familiar with Java.
96 readers like this.

After years as an educator, I became a professional software developer. That brought me to Java, but recently, I began enjoying a totally different but compatible programming language called Kotlin.

Kotlin is a cross-platform, general-purpose programming language that runs on the Java Virtual Machine (JVM). JetBrains led its implementation, which began in 2010, and it has been open source since early in its development.

The great news for Java developers is that Kotlin is interoperable with Java. Standard Java code can be included in a Kotlin program, and Kotlin can be included in a Java program. That immense investment in compatibility means if you come from a Java background, picking up Kotlin will feel familiar and be a low risk since it will run alongside any of your existing Java code.

To introduce you to Kotlin, I will go over some of its basic syntax, ranging from variables to defining functions and classes. If you want to follow along and learn some of the language's features, there is a great browser-based Kotlin playground you can use.

Variables

Variables in Kotlin will feel familiar. Here are a few examples of creating basic integers:

var I = 5
val j = 7
var k:Int = 8

There's a subtle and important difference between var and val assignments: var is used when the variable you defined can be reassigned, and val is used for local scope values that will not be changed. Each variable's type is optional because the type can be inferred, similar to the dynamic assignment in JavaScript. There are also nullable assignments that use syntax like:

var f: Int? = 9

This means the assigned value can be equal to null. The reason for using null is outside the scope of this article, but it's important to know that a variable can only equal null when explicitly defined to do so.

If you plan to define a variable with no initial instantiation (value), you must place the type after the variable name:

var s: Int

Strings are composed similarly, with the type after the variable name:

val a:String = "Hello"

Strings have superpowers in Kotlin. They include awesome string template functions that you can explore.

Arrays

Another basic type is the array. It can store a pre-determined amount of objects of the same defined types. There are a few different ways to create arrays in Kotlin, such as:

val arrA = arrayOf(1,2,3)
val arrB = arrayOfNulls<Int?>(3)
val arrC = Array<Int?>(3){5}

The first creates an array with a length of three and the elements 1, 2, and 3; the second creates an array of nulls of type nullable integer; and the third creates an array of nullable integers with each of the elements equaling 5.

To retrieve one of the elements, use bracket notation, starting with zero. Therefore, to retrieve the first element in the first array, use: arrA[0].

Collections

Other ways to group objects in Kotlin are generally referred to as collections. There are a few types of collections in Kotlin. Each can either be mutable (changeable/writable) or immutable (read-only).

  • Lists: An ordered group of items can contain repeated items and must be of the same type. Mutable lists can be formed like this:
    var mutList = mutableListOf(7,5,9,1)
    val readList = listOf(1,3,2)
  • Maps: Maps, similar to HashMaps in Java, are organized by keys and values. Keys must be distinct. They are instantiated like:
    var mapMut = mutableMapOf(5 to "One", 6 to "Five" )
    val mapRead = mapOf(1 to "Seven", 3 to "six")
  • Sets: Sets are a data structure where each object in the group is unique. They are created like this:
    var setMut  = mutableSetOf(1,3, 5, 2)
    val readSet = setOf(4,3,2)

Whenever you try to reassign an immutable object, you will get a syntax error stating Val cannot be reassigned. This behavior comes in handy when you have a collection that you never want to be edited by any part of the program.

Functions

Functions are the foundation of a well-formed software program. Repeatable bits of code stored as functions can be reused without rewriting the same commands over and over again. In Kotlin, the standard syntax for creating a function is:

fun doSomething(param1:String): Unit{
println("This function is doing something!");
}

This example function accepts a string as the only parameter; as you can see, the parameter type is placed after the name of the parameter. The Unit object is the Kotlin equivalent to Java's void when a function does not return a value (although Unit is one value—and only one value—because it is a singleton). Kotlin functions work much as they do in Java and some other languages.

Classes

Classes in Kotlin are very similar to classes in other object-oriented programming (OOP) languages that consider the object/class the foundational building block. Classes are created using the syntax:

class ExampleClass{}

By default, classes possess a primary constructor that can be used to set object properties without writing code for getters/setters (accessors/mutators). This makes it easy to create an object and begin using it without much boilerplate code. The primary constructor cannot contain implementation code, only parameters:

public class ExampleClass constructor(type:String)

To write primary constructor implementation, you can use init within the classes:

init{
val internalType:String = type
}

Or you can initialize it in the constructor by placing val or var in front of each parameter:

public class ExampleClass constructor(var type:String, var size:Int)

Although this didn't go deep into classes, properties, and visibility modifiers, it should get you started creating objects in Kotlin.

The "main" point

Kotlin files have .kt file endings. To begin running a Kotlin file, the compiler looks for a main function within the file; therefore, a basic "Hello World" program would look like this:

fun main(args:Array<String>){
println("Hello World")
}

Easy peasy, right?

Kotlin is an advanced—but intuitive—OOP language that simplifies and streamlines Java development for mobile devices, server-side, web, and data science applications. I find its syntax and configuration much simpler than Java's.

For example, compare the print statement in Java:

System.out.println("Hi")

Versus Kotlin's syntax:

println("Hello")

In addition, getters and setters don't require additional libraries for simple implementation. In Java, libraries like Lombok simplify class/object property setting through annotation. In Kotlin, a class can be implemented with properties easily:

class Person {
	var firstName: String =""
	var lastName: String =""
	var age: Int? = null
	var gender: String? = null
}

These properties can be retrieved or set using the syntax:

var me = Person()
me.firstName = “Stephon”
me.lastName = “Brown”

Kotlin's simplicity and Java interoperability equate to little risk that you will spend time learning something that isn't useful. After taking your first steps into Kotlin, you may never look at your Java code or the JVM the same way again.

What to read next

Why I use Java

There are probably better languages than Java, depending on work requirements. But I haven't seen anything yet to pull me away.

Tags
User profile image.
Stephon currently serves as a Developer Consultant. He spends days with his family practicing Tae Kwon Do, tinkering with new technologies, and researching topics to write about.

7 Comments

Why I will stick with Java?
What Stephon Brown said :D

Hi Stephon,

I really liked the article. I have a question. Is prior Java programing knowledge required to learn Kotlin ?

I learned Java in college but never worked with it professionally. If I want to develop Android apps, can I start with Kotlin ?

Thanks

Ciao!

In my opinion, I would have to say no. Java is not a prerequisite to learning Kotlin.

Knowing Java will demystify a lot of architectural aspects related to the JVM and provide you with extended libraries within Java, but it is not necessary to have a complete and deep understanding to use Kotlin.

Jet Brains even offers very thorough walkthroughs called Koans: https://kotlinlang.org/docs/tutorials/koans.html

In reply to by Learner

I fail to see the property getters and setters in the last paragraph? Actually I have a feeling that the author has no idea what they are.
Otherwise, I'm very unimpressed by Kotlin. var or val, keyword for everything, unclear typing... this thing is a mess.
If you want a nice language, look at Typescript.

Hi Milan,

The getters/setters are automatically implemented once you declare a property within a class; therefore, using the example from the article, me.firstName can be used to both retrieve and set the property "firstName." Moreover, you can make more complex implementations of the property with different syntax outlined here: https://kotlinlang.org/docs/reference/properties.html.

While I agree some aspects of Kotlin may be a bit unclear/complex at first glance, I don't agree that Typescript is as easy to grasp transitioning from Java, an OOP language, provided its subset is the prototype-based language Javascript.

In reply to by Milan (not verified)

Great article!!

One question, what about abstractions like interfaces, abstract classes to support Design Patterns, everything is supported with Kotlin? BTW, why not Scala instead of Kotlin?

Cheers,

Hi Bruno,

Abstractions are backed right into Kotlin: https://kotlinlang.org/docs/reference/interfaces.html
They use some of the same keywords as Java, and you could just make a POJO if you want to shy away from the Kotlin syntax and create your abstractions that way.

As for Scala, I honestly didn't look too much into it. After programming in Java, I was really drawn in by the succinct and simple syntax of Kotlin. I did see Scala is a JVM compatible language and the syntax is very reminiscent of Java, but I wanted to try something different.

In reply to by brunoamuniz

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.