Why I switched from Java to Kotlin | Opensource.com

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.

Person drinking a hot drink at the computer
Image credits : 
x

Subscribe now

Get the highlights in your inbox every week.

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.

Coffee beans

There are probably better languages than Java, depending on work requirements. But I haven't seen anything yet to pull me away.
Learning and studying technology is the key to success

Stop writing loops in Java by using Streams and Collectors

Topics

About the author

Stephon Brown - Stephon currently serves as a Programming Analyst/.Net Developer. He spends days with his family practicing Tae Kwon Do, tinkering with new technologies, and researching topics to write about.