For programmers, testers and tech geeks

Exciting features of Kotlin

In Google IO 2017 event, there has been announced that Android studio 3.0 officially available with Kotlin language which is exciting right. Kotlin the statically typed language have some great features to try out so let’s see those with an example.

No more need findViewById()
Kotlin team has created an extension by using which there will not be any need to use findViewById() instead the id defined in the xml will act as an object name in java or kotlin file. Add the following line to your file over class name.

import kotlinx.android.synthetic.main.activity_main.*

Data class
Instead of writing model classes with getter and setter with each property just use single line in kotlin just add data in front of class and that will become a model class no need for any getters and setters you can directly access the member itself.

data class Employee(internal val name:String, internal val id:Int)

Function with Multi-value return
There comes situation where more than 1 value need to be returned form the function so with kotlin it’s possible to do this.

val employee = Employee("Jhon",24)
val (name,id) = ch(employee)
println(name)
println(id)

Function with default and named arguments
With named argument we can easily change the sequence of the parameter at the time of calling this is done by writing the name of the argument and than assigning the value to it.

fun addAmount(num: Int, str: String = "12") {
}

Extension function
As it’s name indicate this adds some extra feature to the existing component and why do they call it function is because you create a function to add some features where that acts as an extension to the existing component.

fun Int.modify() = this * 2
10.multi()

Null safety
The known mistake "null pointer exception" can easily be avoided with kotlin using ?. operator. The way it works is that it first check for the value if is it null or not if it’s not null than only it perform the next action.

val str:String? = "Description"
str = null
str.length //This will show error.
str?.length //This is valid.

Summary 

Kotlin is a new JVM language fully interoperable with Java byte-code. It is clearly inspired by Scala, but has a different design philosophy, a much gentler learning curve and some really helpful features like null-safe types. For code snippets you can visit : http://www.codeinbit.com/