The best features of Kotlin!

Pankaj Rai 🇮🇳
AndroidPub
Published in
5 min readMay 20, 2017

--

Kotlin is the statically typed language which is having some great features to try out so let’s see those with an example and also how to use kotlin.

Extension function:
As it’s name indicate this adds some extra functionality to the existing component.
Have a look below we are adding an extra functionality to integer which multiplies any number with 5.

fun Int.multi() = this * 5print(50.multi())

This will print 250 as a result
Now let’s add a welcome text using extension function

fun String.greet():String {
return this.plus(" we welcome you!")
}
print("Jhon".greet())

This will print Jhon we welcome you!

High order function
If your function accepts function as a parameter or returns function as a result than it’s called high order function. Let’s see example on how to use high order function

fun addValue(operation:(Int,Int) -> Int):Int {
return operation(10,20)
}
addValue{num1,num2 -> num1 * num2} //This will print 200
addValue{num1,num2 -> num1 - num2} //This will print -10

This is very basic example of high order function which accepts function as a parameter, here operation is the name of the function.

Inter-operable with java
What makes kotlin more interesting is that whatever extra advantage that you have in kotlin it can be used directly in your java code also. If you want to use kotlin class in your java class than just create the object for that class as you normally create in java.

class Demo{

fun Int.mul() = this * 10

fun String.greet():String {
return this.plus(" we welcome you!")
}


fun addValue(operation:(Int,Int) -> Int):Int {
return operation(10,20)
}

fun callThis():Int {
return addValue{a,b -> a * b}
}
}

The above functions are defined inside a kotlin class Demo so in order to use this class in java file create an object for this class and start using these functions.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Demo demo = new Demo();
Log.v("Number:",""+demo.callThis());
Log.v("Number:",""+demo.greet("Jack"));
Log.v("Number:",""+demo.mul(25));
}
}

Null safety
The billion dollar 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 operation for example.

val str:String = "name"
str = null // As str is defined as null save it will show error
str.length

By default all the object are null safe so they will not accept null as a value but there are scenarios where the value could be null so for those cases explicitly you need to define them by adding ? after its type.

val str:String? = "name"
str = null
str.length //This will show error as ?. is not used may result in NPE.
str?.length //This is completely valid now.str!!.length //This will produce NPE if str is null.

Smart cast
It’s quite the best feature that you can ask for what this does is that it check for some type and than it will allow to perform all the operation allowed for that particular type like for example if the type is string it will allow copy, length etc operation and on the same object if it detects it’s an integer than it will allow operation done on integer. How do we do that? so for that just use an operator is to check for the type

val n:Any = "Hello"
when
(n) {
is String -> n.length
is
Int -> n.inc()
}

When is just like a switch statement.

Note: smart casts do not work when the compiler cannot guarantee about the variable change between the check and the usage.

Smart cast work on the following scenarios if

  • val is local variable
  • val is private or internal

Default and named arguments
Absence of this feature in java makes the developer to add function overloading concept as all the parameter declared has to be passed by the caller but with this feature you can get rid of all these just by giving the default value to the parameter whom you want to make optional while calling that method and you are free to use thereafter with no bound on giving values to all the parameter. With named argument now you 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 argumentValid(num: Int, str: String = "12") {
}
//All 3 are valid
argumentValid(15, "Hey")
argumentValid(str = "Name", num = 45) //Named argument
argumentValid(45) //usage of default argument

Multi-value return from function
There are few scenario where more than 1 value need to be returned form the function, now it’s possible to do that. This is actually called as destructuring declaration.

data class Student(val name:String, val age:Int)fun studentsFun(student: Student):Student {
return Student(student.name, student.age)
}
val stud = Student("Jhon",24)
val (name,age) = studentsFun(stud)
println(name)
println(age)

Data class
It’s most common in java to create a model class with the getters and setters but with kotlin all need to do is just add data in front of class and that will become a model class no need of any getters and setters you can directly access the member itself.

public class Student {
private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

This model class in java is same as following model in kotlin

data class Student(internal val name:String, internal val age:Int)

No more findViewById()
There is also a kotlin extension available which eliminates the need of findViewById. Just add apply plugin: ‘kotlin-android-extensions’ in app.gradle

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

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Checking checking = new Checking();
tvValue.setText(String.valueOf(checking.callThis()));
}
}

If you have observe than with the import library line activity_main.* is written well it’s because the xml name here is activity_main that means all the object used in the class is taken from that xml file.

To figure out how to use kotlin for app development download this sample project and keep on experimenting things.

--

--

Pankaj Rai 🇮🇳
AndroidPub

Software Engineer | GDE Android & Firebase | YouTuber — All Techies