Monday 5 July 2021

Android Java to Kotlin migration by example, part 2 (basics, control flow)

This time a bit about Kotlin vs Java syntax. I assume you know Java basics: In this post I'll present some very basic examples of Java code and their Kotlin counterparts.

Hello World

Java "Hello World" looks like this:

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

Kotlin "Hello World" looks like this:

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

In Kotlin it's shorter and we don't have to create a class.

Simple class

We'll get to if and loops in a moment, but first let us create a class, which we can use later for further examples.

Java class definition with one field and one method returning String (using if-else if)

class Human{
    String name;
    
    String saySomething(){
        if(name=="Obi Wan Kenobi")
            return "Hello There";
        else if(name=="Anakin Skywalker")
            return "I don't like sand";
        return "something";
    }
}

Kotlin:

class Human {
    lateinit var name: String
    
    fun saySomething(): String {
        if(name=="Obi Wan Kenobi")
            return "Hello There"
        else if(name=="Anakin Skywalker")
            return "I don't like sand"
        
        return "something"
    }
}

We've already seen most of it: lateinit modifier - it makes it much harder to get a Null Pointer Exception in Kotlin. Method definition looks a but different. Semicolons optional.

Variables and constants

Variable and constant declaration, and then variable assigment in Java:

float floatVar;
final float PI = 3.1415f;
         
floatVar = PI * 2;

Variable and constant declaration, and then variable assigment in Kotlin:

var floatVar: Float
val PI = 3.1415f

floatVar = PI * 2

var and val instead of <<type>> and final type for, respectively: variables and constants declaration.

Conditional operator?

Printing to console and conditional operator in Java:

System.out.println(PI>0?"Pi is positive":"Pi is negative");

Printing to console and if expression, which is analogous to conditional operator, in Kotlin:

println(if(PI>0){"Pi is positive"}else{"Pi is negative"})

println call is shorter... If expression... Well, I guess it's easier to read for novices.

Creating objects

Creating objects in Java:

Human obiWan = new Human();
obiWan.name = "Obi Wan Kenobi";
         
Human anakin = new Human();
anakin.name = "Anakin Skywalker";

Creating objects in Kotlin:

var obiWan = Human()
obiWan.name = "Obi Wan Kenobi"

var anakin = Human()
anakin.name = "Anakin Skywalker"

Kotlin is shorter.

Lists

Creating a list and adding a new object to it in Java:

ArrayList<HumanjediOrder = new ArrayList<>
    (Arrays.asList(obiWan, anakin));

Human luke = new Human();
luke.name = "Luke Skywalker";
         
jediOrder.add(luke);

Creating a list and adding a new object to it in Kotlin:

var jediOrder: MutableList<Human> = mutableListOf(obiWan, anakin)
    
var luke = Human()
luke.name = "Luke Skywalker"
jediOrder.add(luke)

This one is interesting: List in Kotlin is immutable, we need to use MutableList. On the other hand, it's easily initialized. I didn't even remember Java ArrayList initalization to be so complicated.

for loops

Iterating over list by index and using "foreach" in Java:

for(int i=0;i<3;i++)
    System.out.println(jediOrder.get(i).name);
            
for(Human jedi: jediOrder)
    System.out.println(jedi.saySomething());

Iterating over list by index and using "foreach" in Kotlin:

for(i in 0..2)
    println(jediOrder[i].name)

for(jedi in jediOrder)
    println(jedi.saySomething())

That's it for now. To be continued: more control flow, more OOP, other things (exceptions?).


No comments:

Post a Comment

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...