Java to kotlin part -1

Hello Everyone,

The purpose of this post to teach you kotlin syntax and new features based upon your current knowledge of java.

Kotlin is a statically-typed programming language that runs on the Java virtual machine and also can be compiled to JavaScript source code or use the LLVM compiler infrastructure. Its primary development is from a team of JetBrains programmers based in Saint Petersburg, Russia. As of Android studio, 3.0 kotlin is a fully supported programming language as well you can also write a server-side application in kotlin. you can also use kotlin to write build script in the gradle build system.

The best things you can directly use Java classes and library into kotlin and vice-versa

so let’s jump into code.

# print hello world

Java

public static void main(String[] args) {

    System.out.println("Hello World!");
}

Kotlin

fun main(args : Array)
{
    println("Hello World!")
}

# using variable 

Java

public static void main(String[] args) {

    final int a =1;
    final int b = 2;
    final int c;
    c = 3;
    int d =4;

    System.out.println(String.format("a = %d, b = %d, c = %d, d = %d", a, b, c, d));
}

Kotlin

fun main(args : Array)
{
    val a: Int = 1  // immediate assignment
    val b = 2   // `Int` type is inferred
    val c: Int  // Type required when no initializer is provided
    c = 3       // deferred assignment
    var d = 4  //Mutable variable
    println("a = $a, b = $b, c = $c, d = $d")
}

#using function with return and no parameter 

Java

public String message()
{
    return "Hello World";
}

Kotlin

fun message() : String
{
    return "Hello World"
}

#using function with void type and parameter 

Java

public void message(String message)
{
    System.out.println(message);
}

Kotlin

fun message(message : String) : Unit
{
    println("Hello World")
}

//or

fun message(message : String)
{
    println("Hello World")
}

#using conditional expression

Java

public int maxValue(int a, int b)
{
    if(a > b){
        return a;
    }else {
        return b;
    }
}

Kotlin

fun maxValue(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

#using switch case(in case of kotlin we can using ‘when’)

Java

switch (args)
{
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        break;
        default:
           System.out.println("args is not 1 or 2");

}

Kotlin

when(args){
    1 -> println("One")
    2 -> println("Two")
    else -> {
        println("args is not 1 or 2")
    }
}

#using for loop

Java

String[] arrays = {"Apple", "Mango", "Orange"};
for(int i=0;i<arrays.length;i++)
{
    System.out.println(String.format("item at %d is %s",i,arrays[i]));
}

Kotlin

val items = arrayOf("Apple","Mango","Orange");
for (index in items.indices)
{
    println("item at $index is ${items[index]}")
}

#using while loop

Java

String[] arrays = {"Apple", "Mango", "Orange"};
int index = 0;
while(index < arrays.length)
{
    System.out.println(String.format("item at %d is %s",index,arrays[index]));
    index++;
}

Kotlin

val items = arrayOf("Apple","Mango","Orange");
var index =0
while (index < items.size)
{
    println("item at $index is ${items[index]}")
    index++
}

#using lambda

Java

String[] strArray =  {"Avocado","Mango","Apple","Orange","banana","Guava"};
List fruits = Arrays.asList(strArray);
fruits.stream().filter(s->s.startsWith("A")).sorted().map(s->s.toUpperCase())
        .forEach(s->{
            System.out.println(s);
        });

Kotlin

val fruits = arrayOf("Avocado","Mango","Apple","Orange","banana","Guava")
 fruits.filter { it.startsWith("a") }.sortedBy { it }.
         map { it.toUpperCase() }.forEach{ println(it)}

#using null values and checking for null

Java

public Integer parseInt(String str)
{
    try {
        return Integer.parseInt(str);
    }catch(NumberFormatException ex)
    {
        return null;
    }
}

Kotlin

fun parseInt(str: String) : Int?
{
    return str.toIntOrNull()
}
//incase if you call parseInt method with null input
fun parseInt(str: String?) : Int?
{
    return str?.toIntOrNull()
}

#using type checks

Java

public Integer getStringLength(Object obj)
{
    if(obj instanceof String)
    {
        return ((String) obj).length();
    }

    return null;
}

Kotlin

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

Ref –  Kotlin docs

Part-2

Thanks for reading 🙂

Advertisements