Kotlin : some cool features

Let's Get The Job Done!

Kotlin : some cool features

Let’s take a look at some of kotlin‘s cool features here , gathered from multiple sources across web , i personally hope that kotlin replaces java in android totally.

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 * 5 
print(50.multi())

 

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

So cool !

 

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.

So cool too !

 

Null safety

simply an object could not be null by default , and if you assign a null value to an object the compiler throws an error , except that you explicitly declare an object to be null by ? operator:

val myStr : ?String = "whatEver"

 

Smart cast

It’s quite the best feature that you can ask for what this does is that it check for some type and then 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

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

Smart cast work on the following scenarios if

  • val is local variable
  • val is private or internal
 

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)

 

 

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/studentName"
        android:padding="8dp"
        android:textSize="24sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

 

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(); 
           studentName.setText(String.valueOf(checking.callThis())); 
         }
 }

soooooooo cool !

 

 

Elvis Operator

You can work with nullable types more effectively by using the “Elvis Operator”.

val len = x?.length ?: -1

In this case if x is not null its length will be used, otherwise -1 is used (as it is a default value).

 

Singleton :

Another interesting Kotlin feature is the simplicity of defining “singleton”. Consider the following example of how singleton could be created in Java.

public class SingletonInJava { 
    private static SingletonInJava INSTANCE; 
    public static SingletonInJava getInstance() { 
        if (INSTANCE == null) {
            INSTANCE = new SingletonInJava(); 
        }
        return INSTANCE; }
    }

Kotlin has a feature to define a singleton in a very clever way. You can use a keyword  object which allows you to define an object which exists only as a single instance

object SingletonInKotlin { } // And we can call SingletonInKotlin.doSomething()

 

 

Default Parameters:

One very annoying part of Java is the way methods have to be overloaded. Let’s see an example:

public class Overloade 
    public static void main(String[] args) {
        Overloader o = new Overloader(); 
        o.testWithoutPrint(2); o.test(2); } 
    public void test(int a, boolean printToConsole) {
        if (printToConsole) System.out.println("int a: " + a); 
       } 
    public void testWithoutPrint(int a) { 
        test(a, false); } 
    public void test(int a) { test(a, true); 
   }
}

We can see a class with a method test(int, boolean) that is overloaded for the default case and also a convenience method is available. For more complex examples, it can lead to a lot of redundant code, which is simpler in Kotlin by using default parameters.

fun test(a: Int, printToConsole: Boolean = true)
 { if (printToConsole) println("int a: " + a) } 
fun testWithoutPrint(a: Int) = test(a, false) 
fun main(args: Array) { testWithoutPrint(2) test(2) }

 

with() and apply()

with() allows you to pass a function as a parameter in which you can call members of an instance as if you were writing code within a class of this instance. Basically, instead of having this:

fun updateText(textView: TextView) {
  textView.visible = View.VISIBLE
  textView.text = "Hello world"
  textView.setOnClickListener {
    // Do stuff
  }
}

You can have that:

fun updateText(textView: TextView) {
  with (textView) {
    visible = View.VISIBLE
    text = "Hello world"
    setOnClickListener {
      // Do stuff
    }
  }
}

if textView is nullable we can use apply() instead:

fun updateText(textView: TextView?) {
  textView?.apply {
    visible = View.VISIBLE
    text = "Hello world"
    setOnClickListener {
      // Do stuff
    }
  }
}

 

Overloaded operators for collections

Aren’t they awesome? Yet somehow I missed this feature initially.

fun listItemsToDisplay(): List<ListItem> {
  return listOf(ListItem.Header) + closestVehicles() + recentSearches() 
}

 

Defining a map

From time to time, there is a need to define some hardcoded Map. There are several ways to do them in Java. That would be the most straightforward one:

// normal code
val hashMap = HashMap<String, String>()
hashMap.put("keyA", "valueA")
hashMap.put("keyB", "valueB")
hashMap.put("keyC", "valueC")

The better way

val map = mapOf(
  "keyA" to "valueA",
  "keyB" to "valueB",
  "keyC" to "valueC"
)

 

 

sources :

 The best features of Kotlin!

Kotlin Features I miss most in Java – Kotlin vs Java

 Kotlin Features You Should Use Now

4 Kotlin tricks we use in car2go