Tips to migrate to Kotlin from Java
Tags: kotlin, java
Published: 2020-09-15 21:44:58

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](https://dev.to/alexfelipe/dicas-na-migracao-de-java-para-kotlin-2dep).

## Running the program only with a function

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

```java
class Main {

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

}
```

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

With the Kotlin, we have a different approach:

```kotlin
fun main() {
    println("Hello World!")
}
```

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:

```kotlin
var name = "Alex"
name = "Alex Felipe"
val age = 26
age = 26 // doesn't compile
```

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:

```kotlin
var name = "Alex"
name = 10 // doesn't compile
```

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

```kotlin
var name: String = "Alex"
name = "Alex Felipe"
val age: Int = 26
age = 26 // doesn't compile
```

## 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:

```java
class Person {
    private String name;
    private int age;

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

We can create a object this way using Kotlin:

```kotlin
val alex = Person("Alex", 26)
val fran = new Person("Fran", 25) // doesn't compile
```

> 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:

```java
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;
    }
}
```

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

With properties, this is behavior the default:

```kotlin
class Person {
    var name: String
    var age: Int

    constructor(name: String, age: Int){
        this.name = name
        this.age = age
    }
}
```

> [Kotlin has more than one constructor](https://kotlinlang.org/docs/reference/classes.html#constructors), 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:

```java
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
    }
}
```

Running the sample code below:

```kotlin
val alex = Person("Alex", 26)
alex.name = "Alex Felipe"
println(alex.name)
```

We get the following result:

```
Setting the name Alex
Setting the name Alex Felipe
Getting the name Alex Felipe
Alex Felipe
```

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.

```kotlin
set(value) {
    println("Setting the name $value")
}
```

Doing the same test, we get the follow result:

```
Setting the name Alex
Setting the name Alex Felipe
Getting the name null
null
```

## 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`](https://kotlinlang.org/docs/reference/basic-types.html#string-templates), 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:

```kotlin
println("1 + 2 = ${1 + 2}")
```

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

```
1 + 2 = 3
```

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

```kotlin
println("My name is ${alex.name}")
```

## 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 😉