DEV Community

Cover image for Tips to migrate to Kotlin from Java
Alex Felipe
Alex Felipe

Posted on • Updated on

Tips to migrate to Kotlin from Java

If you develop software with Java and are interested in leaning Kotlin, you have probably checked out some Kotlin code, especially if you know Android.

Besides language similarities, there are few differences that seems confusing, but believe me, they come to help us!

Therefore, I'll use this article to share some differences between Kotlin and Java, focusing on things for people who want to Kotlin, are you interested? So let's get to it.

This article is a translation of the article written in brazilian portuguese. You can check out the original here.

Running the program only with a function

When writing a Java code and running it, we have our first impact:

class Main {

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

}
Enter fullscreen mode Exit fullscreen mode

Even if your program only prints a message, the main method is very verbose.

With the Kotlin, we have a different approach:

fun main() {
    println("Hello World!")
}
Enter fullscreen mode Exit fullscreen mode

That's it, this code is enough to run our Hello World!.

A valid note: we don't need the ; on final of statement, it's optional and unnecessary.

Variable declaration and its types

When variables are declared in Kotlin, we must decide if it will be mutable or not, being var mutable and val immutable:

var name = "Alex"
name = "Alex Felipe"
val age = 26
age = 26 // doesn't compile
Enter fullscreen mode Exit fullscreen mode

This is one of the things that I like about Kotlin the most, because the effort to keep the immutability in code base is way less than Java approach that use final to do it.

Also note there is no need to declare a variable type.

"Does this mean that variables are dynamically-typed?"

Just like Java, Kotlin is statically-typed, in other words, when a variable receives a value, implicitly a type is set even if the variable doesn't have a type explicitly declared.

Therefore, the code below, doesn't compile:

var name = "Alex"
name = 10 // doesn't compile
Enter fullscreen mode Exit fullscreen mode

If you love writing explicit code, don't be sad. Kotlin also allows you to declare a variable type:

var name: String = "Alex"
name = "Alex Felipe"
val age: Int = 26
age = 26 // doesn't compile
Enter fullscreen mode Exit fullscreen mode

Creating objects

When working with Object Oriented languages the need to create objects is natural, and in Java we need use new to do so. But Kotlin the new is not even a keyword!

"So how do we create a Kotlin object?"

Considering this Java class:

class Person {
    private String name;
    private int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Enter fullscreen mode Exit fullscreen mode

We can create a object this way using Kotlin:

val alex = Person("Alex", 26)
val fran = new Person("Fran", 25) // doesn't compile
Enter fullscreen mode Exit fullscreen mode

This means that variables with the name new can be compiled on Kotlin.

Properties instead attributes

Besides the differences in instance creation, the Kotlin made some changes with class declaration. In this Person class example, we have the name and age attributes to store the object state.

This approach is too many common in Java and several OO languages. However, in Kotlin, instead declare attributes, we declare properties!

"But what's the difference between attribute and a property?"

The main difference is how attributes are accessed. When working with attributes, a good practice is implement access methods as getters and setters to read or write:

class Person {
    private String name;
    private int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this way, we avoid attributes manipulation directly on the class without a possible filter.

With properties, this is behavior the default:

class Person {
    var name: String
    var age: Int

    constructor(name: String, age: Int){
        this.name = name
        this.age = age
    }
}
Enter fullscreen mode Exit fullscreen mode

Kotlin has more than one constructor, the primary and secondary. In this implementation I used the secondary, but the primary is the most common.

In other words, when we access name or age from a Kotlin class, actually we're accessing the setter and getter! Much simpler, right?

In addition, in Java if you try to access Kotlin properties, you will see only the setters and getters 😁

Modifying the set and get of properties

This difference may sound weird at first, but to be more clean, we can declare the access methods of properties:

class Person {
    var name: String
    set(value) {
        field = value
        println("Setting the name $value")
    }
    get() {
        println("Getting the name $field")
        return field
    }
    var age: Int

    constructor(name: String, age: Int){
        this.name = name
        this.age = age
    }
}
Enter fullscreen mode Exit fullscreen mode

Running the sample code below:

val alex = Person("Alex", 26)
alex.name = "Alex Felipe"
println(alex.name)
Enter fullscreen mode Exit fullscreen mode

We get the following result:

Setting the name Alex
Setting the name Alex Felipe
Getting the name Alex Felipe
Alex Felipe
Enter fullscreen mode Exit fullscreen mode

Notice that even the class itself, during object construction, also directly access the setter of the property!

Another point to take note, inside of set and get, we used the field to assign and get the property value, i.e, the field represents the real attribute and only can be accessed into property scope!

Therefore, if we don't modify the field value, the real property value doesn't change.

set(value) {
    println("Setting the name $value")
}
Enter fullscreen mode Exit fullscreen mode

Doing the same test, we get the follow result:

Setting the name Alex
Setting the name Alex Felipe
Getting the name null
null
Enter fullscreen mode Exit fullscreen mode

Template String

Another thing about Kotlin, is the way how to concatenate the String.

Note that we put all content under "" without using the + operator.

This technique is called as Template String, also known as string interpolation in other languages.

Basically, through the Template String, we can embed code into String, either to only read a value or run a statement that return a value:

println("1 + 2 = ${1 + 2}")
Enter fullscreen mode Exit fullscreen mode

In this case, we need to put the all code in {} and we get the follow result:

1 + 2 = 3
Enter fullscreen mode Exit fullscreen mode

This rule is necessary when we access object's members too:

println("My name is ${alex.name}")
Enter fullscreen mode Exit fullscreen mode

Conclusion

Besides the tips in this articles, Kotlin offers many other features and differences compared to Java. Most of them were made to help us write and read less code and gain more results!

Did you like these tips? If yes, leave your like, do a comment and share this article 😉

Top comments (1)

Collapse
 
ender_minyard profile image
ender minyard

Thanks for the helpful tips!