Monday, April 1, 2019

Kotlin - Control Flow - when

Greetings!

Just like if, when also an expression. It has 2 forms.
  • With a value - behave as a switch operator.
  • Without a value - behave as if-else-if chain.

when as a switch

Java

private void dayOfWeek(int dayOfWeek) {
    switch (dayOfWeek) {
        case 1:
            System.out.println("Sunday");
            break;
        case 2:
            System.out.println("Monday");
            break;
        case 3:
            System.out.println("Tuesday");
            break;
        case 4:
            System.out.println("Wednesday");
            break;
        case 5:
            System.out.println("Thursday");
            break;
        case 6:
            System.out.println("Friday");
            break;
        case 7:
            System.out.println("Saturday");
            break;
        default:
            System.out.println("Invalid day");
    }
}

Kotlin

private fun dayOfWeek(dayOfWeek: Int) {
    when (dayOfWeek) {
        1 -> println("Sunday")
        2 -> println("Monday")
        3 -> println("Tuesday")
        4 -> println("Wednesday")
        5 -> println("Thursday")
        6 -> println("Friday")
        7 -> println("Saturday")
        else -> println("Invalid Day")
    }
}

How pretty is that?

Combine multiple branches

private fun whatDay(dayOfWeek: Int) {
    when (dayOfWeek) {
        2, 3, 4, 5, 6 -> println("Weekday")
        1, 7 -> println("Weekend")
        else -> println("Invalid Day")
    }
}

Using in operator

private fun examResult(marks: Int) {
    when (marks) {
        in 1..60 -> println("You failed")
        in 60..100 -> println("You passed")
        else -> println("Invalid number")
    }
}

when as an if-else-if

Java

private static void printType(int number) {
    if (number < 0) {
        System.out.println("Negative number");
    } else if (number % 2 == 0) {
        System.out.println("Even number");
    } else {
        System.out.println("Positive odd number");
    }
}

Kotlin

private fun printType(number: Int) {
    when {
        number < 0 -> println("Negative number")
        number % 2 == 0 -> println("Even number")
        else -> println("Positive odd number")
    }
}

when as an expression

We can return or assign the value of when expression.
private fun racer(speed: Int): String {
    return when {
        speed in 0..24 -> "Beginner"
        speed in 24..30 -> "Intermediate"
        speed in 30..41 -> "Average"
        speed > 41 -> "Pro"
        else -> "Invalid speed"
    }
}


Kotiln - Control Flow - If

Greetings!

If is the most basic way to control flow in Kotlin. Unlike Java, in Kotlin if is an expression. That is it return a value.
  • Statement - is a program instruction that return no value. Can't be on right side of the equal sign.
  • Expression - is a program instruction that return values. Can be assign to a variable.

Java

private void findMax(int a, int b) {
    int max;
    if (a > b) {
        max = a;
    } else {
        max = b;
    }
    System.out.println("Max value is " + max);
}

Kotlin (traditional statement)

private fun findMax(a: Int, b: Int) {
    val max: Int
    if (a > b) {
        max = a
    } else {
        max = b
    }
    println("Max value is $max")
}


Kotlin (as an expression)

private fun findMax(a: Int, b: Int) {
    val max: Int = if (a > b) {
        a
    } else {
        b
    }
    println("Max value is $max")
}


Ternary Operator

Kotlin doesn't have a ternary operator. It's because result of if, else can be assigned to a variable.

Java
private void findMax2(int a, int b) {
    String result = (a > b) ?  a + " is greater than " + b : b + "is greater than " + a;
    System.out.println(result);
}

Kotlin
private fun findMax2(a: Int, b: Int) {
    val result = if (a > b) "$a is greater than $b" else " $b is greater than $a"
    println(result)
}

Return it

private fun directReturn(age: Int): String {
    return if (age < 21) "You are a kid" else "You are an adult"
}


Sunday, March 31, 2019

Kotlin - Variables and Type Inference

Greetings!

Unlike Java, Kotlin uses special keywords to declare variables.
  • var - for the values that change, mutable.
  • val - for the values that do not change, immutable.

Java
String name = "Java";
int age = 20;

Kotlin
val name = "Kotlin"
val age = 4

It is best practice to use val because immutability guarantees safety.

We can use variable type when we declare it. If we initialize it, we can remove the type. But if we do not initialize, we should declare the variable type.
val name = "Jon Snow"

val role: String
role = "King in the north"

Constant

If the value is a truly constant we can const keyword when declaring. Though this needs to use companion object.
const val THE_END = "All men must die"

Type inference

Kotlin is a strongly typed language. Compiler can deduce the type by the context eliminating boilerplate code. Compiler is smart enough to identify the variable type.
val helpUs = "Save Wilpattu"
val pi = 3.14

println(helpUs::class.simpleName)
println(pi::class.simpleName)

It will print String and Double.



Kotlin - Introduction

Greetings!

I'm going to talk about Kotlin as a Java developer. There are many languages looming and Kotlin is one of them. Since it is another JVM based language it will be easier to grasp.

Why another language?

Java is more than 20 years old mature, widely used language. The problem of being old is it lacks modern techniques. Even though Java adapted to functional programming with Java 8, I believe it is somewhat late for the game.
Considering modern day language features, difficulties they have faced using Java, Jetbrains created Kotlin. Being the one of the best IDE providers they know what they are doing. With InteliJ Idea Kotlin has the best IDE support with it.

What is Kotlin

Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of its standard library depends on the Java Class Library, but type inference allows its syntax to be more concise.
(Wikipedia)

Java disadvantages

  • Lack modern day programming features.
  • Disappointed/ forced exception handling.
  • Boilerplate codes.
  • Unnecessary getter and setters.

Kotlin advantages

  • Modern features.
  • 100% compatible with Java.
  • Interoperable, leverage existing libraries for the JVM, Android and browser.
  • Better exception handling (specially null pointers).
  • Concise, clean easy to read code.

Kotlin = Java + modern features

Hello World

Java
package com.slmanju.blog;

public class Hello {

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

}

Kotlin
package com.slmanju.blog

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

As you can see, Kotin is a beauty.