Kotlin and Android

Kotlin is an official language for Android, which is announced in Google I/O . It's expressive, concise, and powerful. Best of all, it's interoperable with our existing Android languages and runtime.

Watch this here


Kotlin Features :


Concise
Java has lots of boiler plate code in its structure. Using kotlin we can get rid of this. This will increase the code readability and understandability. So we need to write less number of code to do the same code compared JAVA.
                
    Kotlin

    button.setOnClickListener {
            Toast.makeText(this, "Button Clicked", Toast.LENGTH_LONG).show();
    }
    
                
                
    JAVA

    button.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
             Toast.makeText(this, "Button Clicked", Toast.LENGTH_LONG).show();
        }
     });
 
                

Null safety
We will get lot of crashes due to NullPointerException in JAVA. To handle that Kotlin introduced a features called "Null safety". Which will eliminate the NullPointerException drastically.
                
    var a: String = "abc" // Declaring var 'a' as String ( If we declare var 'a' as String? then it can accept null
    a = null // compilation error 
 
                
Interoperable
Kotlin follows same byte code structure of JAVA. So we can use Kotlin and JAVA codes in a project at same time. We can access JAVA code from Kotlin and vice versa.
Higher order functions
we can pass function as a parameter to another function.
                
    fun Calculator(val1:Int,val2:Int,operation :(Int,Int)->Int){
        val result = operation(val1,val2)
        println(result)
    }

    fun main(args:Array){
        val add: (Int,Int) -> Int ={ a,b -> a+b}
        val sub: (Int,Int) -> Int ={ a,b -> a-b}
        Calculator(5,5,add) // Print the value 10
        Calculator(5,5,sub) // Print the value 0
    }
 
                

12800 Subscribers