Developer guide for migration from Java to Kotlin for Android

AN ARTICLE BY Anil Raavi (SOFTWARE ENGINEER, AUGMENTED REALITY, MOBILIYA)

Kotlin:  Overview and background

 Kotlin is a statically typed programming language for the JVM, Android and the browser. Its primary development is from a team of JetBrains programmers. Kotlin is being promoted by Google Android

Why use Kotlin for Android Development?

Concise: Drastically reduces the amount of boilerplate code we need to write

Safe: Avoid entire classes of errors such as null pointer exceptions

Inter-operable: Kotlin is 100% inter-operable with java. It allows to use all existing Android libraries in a Kotlin application, e.g. Dagger2, RxJava, Databinding etc.

Let’s observe in detailed differences between Kotlin vs Java

 Interoperable with Java:

 When it comes to give a try to a new language, interoperability is a great thing which can help you. Interoperable means you can reuse any Java class ever written, all Java code can work with Kotlin and vice versa. Learning Kotlin for a Java developer shouldn’t be too hard. Everything you can do with Java, you can do in Kotlin. If you do not know how to do it in Kotlin, then just do it in Java and let the Kotlin plugin convert it to Kotlin. Make sure that you see what happened to your code, so that the next time you can do it yourself.

Null Safety:

Kotlin’s type system is aimed to eliminating the danger of null reference from the code. One of the main problem in programming languages including java is that of accessing a member of a null references.

In Kotlin, the type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). For example, a regular variable of type String can’t hold null

var a: String = 123;
a= null // It throws compilation error.

To allow nulls, you can declare a variable as nullable string.

var b : String? = 123;
b = null; // No errors here.

Now if we call any method or access a property on object a, it is guaranteed not to cause a NullPointerException, you can safely call,

a.length;

But if we want to access the same method on object b, that would not be safe, and the compiler reports an error.

val x = b.length // its throws an error , Variable b can be null

To access the methods of b, we need to use safe call operator (?)

val y = b?.length

Smart Casting:

//In java

if (obj instanceof String) {

((String) obj).lengh;}

//In Kotlin

if (obj is String)   {

obj.length; // Here is smart casing, no need of casting.}

Concise code:

When you use Kotlin instead of java, there is a huge reduction of code in your project

For example,

// Java

Button button =(Button) findViewById (R.id.button);

button.setOnClickListener(new View . OnClickListener () {

@Override

public void onClick(View view) {

/* your code */  

}

});

// Kotlin

val button = findViewById(R.id.fab) as Button
button.setOnClickListener {view -> /* your code */} 

Favourite features in Kotlin:

 1) Replacing simple if / elseif / else blocks with when,

// Java

if (firstName.equals(Dan)) {
person.setTeam(programmers);
} else if (lastName.equals(Dihiansan)) {
person.setTeam(designers);
} else {
person.setTeam(others);
}

// Kotlin

when {    firstName == Dan”       -> person.team = programmers

lastName == Dihiansan-> person.team = designers

else                     -> person.team = others

}

// Java

Switch (firstName) {   

Case Dan: person.setTeam(programmers)

break;

Case Jay: person.setTeam(programmers)

break;

Case Jamie: person.setTeam(designers)

break;

Default:    person.setTeam(others)

}

// Kotlin

when (firstName) {

Dan, Jay-> person.team = programmers

Jamie-> person.team = designers

else -> person.team = others

}

2) Beautifying even the ugliest click handlers 

Using the Anko,A library built in for Kotlin, click listeners are very easy,

// Java 

view.setOnClickListener(new View.OnClickListener () {

@Override

public void onClick(View v) {

System.out.println(Too much boilerplate code);

}

});

// Kotlin 

view.onClick {   

println(What an easy in kotlin)

}

3) No more View Binding  

By using the Kotlin Android Extensions, you no longer need to bind views to objects to start working with them. You can access them directly without any binding. Zero. None.

// Java

EditText composer = findViewById(R.id.composer);

composer.setText(Hello!”);

// Kotlin

view.composer.text = Hello!” 

4) Convenience methods built on top of familiar objects 

Kotlin has extended objects you’re familiar with and made them even better and packaged them into the Kotlin Standard Library.Take string comparison example,

//Java

if (name.toLowerCase().contains(firstName.toLowerCase())) {\

//…

}

// Kotlin

if (name.contains(firstName, true)) { //… }

Not a huge difference, but enough to improve readability in many places. The standard library has tons of these kinds of tweaks. Perfect!

5) The Elvis operator (?)

The real reason this is great is because it handles the common scenario of “if something is null, I want to give it a value, but otherwise just leave it alone”.

// Java

if (people == null) {

people = new ArrayList();

}

return people;

// Kotlin

return people?: emptyArrayList()

Here if people isn’t null, it returns. If it is, it returns whatever is to the right of the Elvis operator.

Comparative analysis with Java

  • Null references are controlled by the type system
  • No raw types.
  • Arrays in Kotlin are invariant
  • Kotlin doesn’t have checked exceptions

Conclusion

As discussed above, Kotlin is one of the best option, easy to learn, comes with low risks, and we can easily start it alongside with Java. Google has made it official and open source for Android. And its features are fully compatible with Java. I believe Kotlin is an excellent fit for android not only because it gives developers what they want, but also because it matches the spirit of Android.

References

https://kotlinlang.org

https://kotlinlang.org/docs/tutorials/kotlin-android.html

https://developer.android.com/kotlin/index.html

https://youtu.be/NqlRg1_bCC4

Leave a Reply

Your email address will not be published. Required fields are marked *