Sakib Sami' Blog


Newbie programmer, Java fan, Rosogolla lover, Mom's little kid.


Why I perfer Kotlin over Java for Android

First you should know what is kotlin.

Ok, Kotlin is a JVM based statically typed programming language developed by JetBrains.

Now you may what to know whom are JetBrains ?
Well, JetBrains is the creator of Intellj Idea, PhyCharm & few other awesome development tool.

Note the word JVM based. This means kotlin runs on Java Virtual Machine.

Surprised ? If so, then you may want to know if Java & Kotlin both runs on JVM then why people are so excited about Kotlin for Android.
Hmm, That is this post's discussion topic.

I will figure out some points why people (Specially me) prefer Kotlin over Java.

Few Short Note :
-> It's opensource.
-> Kotlin compiles to JVM bytecode or JavaScript.
-> Much smaller learning curve than any other jvm based language.
-> It imposes no runtime overhead.
-> Better IDE support.
-> Kotlin native to run kotlin application without JVM (not supported yet).

1. I am a lazy guy : As I am a very lazy I don't want to write unnecessary code.

Like, Assume we are using a rest api in our app.
How we will call it from Java.

public class UserApi {  
    public static Result callForLogin(String username, String password) {
        // Api call here
    }
}

// calling...

Result result = UserApi.callForLogin("sakib", "12345");  

How we can do it in kotlin ?

// UserApi.kt
// You don't have to create class

fun callForLogin(username: String, password: String) {  
    // Api call here
}

// calling...

val result = callForLogin("sakib", "12345")  

2. Extension function : Assume you want to add few functionality in Integer or String class. What we will do in Java ? You have nothing to do as String & Integer is final class. But in kotlin you can do it easily.

fun Int.str(): String {  
    when (this) {
        0 -> return "ZERO"
        1 -> return "ONE"
        2 -> return "TWO"
        3 -> return "THREE"
        4 -> return "FOUR"
        5 -> return "FIVE"
        else -> return "NOT IMPLEMENTED"
    }
}

uses,

var x = 1  
println(x.str())    // Output : ONE  

str() method is available to object of Int class. This is called extension function in kotlin.

3. My App is full of Singletons : How we implement Singleton pattern in Java,

public class MySingleton {  
    public static MySingleton mySingleton = null;

    public static MySingleton getInstance(){
        if(mySingleton == null) {
            mySingleton = new MySingleton();
        }
    }

    private MySingleton() {

    }
}

uses,

MySingleton mySingleton = MySingleton.getInstance();  

Cool ! How it will look like in kotlin ?

object MySingleton {

}

uses,

val mySingleton = MySingleton  

Still you hate Kotlin ? Ok, Go scroll down.

4. Operator overloading : you can overload operators in Kotlin. Here is an example,

operator fun String.times(times: Int): String {  
    val buffer = StringBuilder()
    for (i in 1..times) {
        buffer.append(this)
        if (i < times)
            buffer.append(" ")
    }
    return buffer.toString()
}
val name = "Sakib"  
println(name * 5)  
// Output : Sakib Sakib Sakib Sakib Sakib

5. Magical class initialization,

class Car(map: MutableMap<String, Any>) {  
    var name: String by map
    var model: String by map
    var year: Int by map

    override fun toString(): String {
        val buffer = StringBuilder()
        buffer.append("name = $name,")
        buffer.append("model = $model,")
        buffer.append("year = $year")
        return buffer.toString()
    }
}

uses,

val map = mutableMapOf("name" to "Corolla", "model" to "G", "year" to 2017)  
val car = Car(map)  
println(car.toString())  
// Output : name = Corolla,model = G,year = 2017

6. Smart cast :

In Java,

if(name instanceof String) {  
    return (String) name;
}

In Kotlin,

if(name is String) {  
    return name
}

7. Functional programming :

val myList = listOf<String>()  
val myMap = mapOf<String, Int>()  

8. Named Argument :

fun multiply(x: Int, y: Int = 1): Int {  
    return x * y
}

uses,

multiply(10, 11)  
multiply(y = 10, x = 5)    // Named Argument  
multiply(10)    // y will consider 1 as given default value  

9. Threading :

thread(start = true) {  
    // New thread
}

You will find more feature here.

Few Android only feature,
Kotlin has a powerful framework named Anko for Android.

Why Anko ?

1. DSL based UI :

verticalLayout {  
    val name = editText()
}

2. Resource binding :

class MainActivity : AppCompatActivity() {  
    private var myBtn: Button by Delegates.notNull<Button>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        myBtn = find(R.id.myBtn)
    }
}

3. Click Listener with kotlin coroutine :

myBtn.onClick {  
    // Simplified toast
    toast("Hello World")
}

4. AsyncTask :

doAsync {  
    // In Background thread
    // Do network call

    uiThread {
        // In UI thread
    }
}

There are still lot of feature you will love about kotlin. Hope you will explore by yourself.

Note : In this year's (2017) IO google announced official support for kotlin on Android. But this doesn't mean they will replace java rather they will keep kotlin with Java. So there's no problem if you are not interested about kotlin.If you are new to programming you should learn Java first. As it will give you better understanding of JVM architecture.

Building custom push notification service with MQTT

MQTT (Message Queue Telemetry Transport) is a lightweight messaging protocol specially designed for…

mqtt, mqtt broker, push notification

Angular2 with MQTT

In package.json add, "ng2-mqtt": "^0.1.2" npm install it will install dependencies. Now in your com…

angular2, angular, mqtt