Kotlin-ize your Android Development

Akshay Chordiya
AndroidPub
Published in
6 min readMar 17, 2017

--

Content

In this article we will look at the current scenario of Android Development with Java and see what’s Kotlin and I will show you why Kotlin is the next best thing for Android. This article is just to give you an idea about Kotlin and in the next articles we will dive more deep into Kotlin stuff.

What’s Kotlin

Kotlin Logo

Kotlin is a new programming language targeting JVM, Android and even JavaScript. It’s made by JetBrains the maker of Suite of the Best IDEs (Personal Opinion).

Unlike other languages targeting JVM, Kotlin takes into consideration the value of Java, the libraries, the architectures and so much previous effort put into Java. Hence Kotlin is 100% inter-operable with Java™ enabling you to consume your previous Java code and libraries in your Kotlin code.

Recently it’s gaining a lot of traction especially in the Android community. Moreover JetBrains is giving special importance to Android. We will be focusing mainly on the Android side.

If you want to know more about Kotlin like why it was developed then refer this article “How effective Java may have influenced the design of Kotlin”.

Current scenario

The most popular and widely used language for Android Development is Java. Sure we can build good Android apps using Java, but there is surely a lot of scope to build better apps. The reason is because Java is old, too much verbose and don’t forget the in-famous NullPointerException (No offense).

Even for building simple apps in Java we end up writing lots of code most of which is just boilerplate.

Boilerplate shock

For Android it’s even worse because all Android versions before Nougat are stuck at Java 6 (kinda). That means we don’t have the Java 8 features like:

  • Lambda expressions
  • Streams
  • Try with resource
  • And a lot more Java 8 goodies 🎁

Surely we can use Java libraries which back-port these features on older versions of Java and can be used in Android. But it’s entirely one’s opinion.

For Android we have even bigger list of problems with Java:

  • Stuck at Java 6–7 (kinda)
  • Very verbose (plenty of boilerplate)
  • Java language restrictions and design problems
  • Null-ability issues (specialty with Android APIs)
  • Inability to add methods to Platform APIs
  • And so much more….maybe you could add more over here ;)
  • Don’t forget the Java’s design flaws
Shouting due to problems in Android

Little bit about the Syntax

In order to understand the features of Kotlin. We will have a look at the basic syntax in Kotlin. You can refer the syntax in detail from the official website, it’s quite concise and simple.

Variables

The way to define a variable is with the “val” or “var” keyword. The type will be inferred from the Context:

val message = "Kotlin Magic"   // String (Implicitly inferred)
val number = 74 // Int

You can specify the type explicitly:

val message : String = "Kotlin Magic" // Explicit definition
var messages: List<String> = ArrayList()

We will see the difference between “val” and “var” ahead in the features of Kotlin.

PS: Did you notice there is no new keyword near ArrayList() ?. Because there is no new keyword in Kotlin

Functions

Structure of the function:

fun add(a: Int, b: Int): Int {
return a + b
}
  • Start with “fun” keyword
  • The parameter names are written before the type
  • The return type is written at the end of the function

The above function can be Kotlin-ized even more:

fun add(a: Int, b: Int) = a + b

This is more idiomatic way of writing the single line functions by just in-lining them. With this we also lose the “return” keyword and the return type is automatically inferred.

PS: Did you notice there are no semicolons(;) ?. Kotlin is semicolon free language

Features of Kotlin

Kotlin has heap of features, I won’t be covering all of them just the important ones to get you started

Null-ability

Kotlin comes with null-safety system which helps in catching null(s) during compile time.
By default every variable is treated as non-null unless we tell to compiler that it’s a null variable using an special operator “?” at the end of the variable type.

While declaring a variable as null:

var message: String = null      // Compile-time error
var message: String? = null // Okay

Using this null variable in further code will also give compile-time error unless handled using not null condition.

message.toUppper()             // Fails to compileif (message != null) 
message.toUpper() // Okay

The compiler is smart enough to understand that we are using an object which can be null-able hence it shows compile time error.

PS: In future examples, we will see how to “Kotlin-ize” the above example.

Mutability

Now it’s time I explained the difference between “val” and “var”.

Use var for something that will vary with time.
Use val for a value that won’t change.

The Compiler even comes with Mutability Protection in order to prevent NPEs on var type variables. We will discuss regarding this in the upcoming articles.

Lambda Expressions

Lambda Expressions are anonymous function which can be passed as an argument to another function. (Higher Order Function).

// Java waymButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Your click logic
}
});
// Kotlin waymButton.setOnClickListener {
// Your click logic
}

With Kotlin we cut to the main logic. It makes our code so clean and simple.

Extension functions

It allows to take a method and transplant it into the an existing class without modifying the original class. Huh! Confused?
Let’s look at an example to clear the picture:

fun Activity.toast(message: CharSequence, duration) {

Toast.makeText(this, message, duration)
.show()
}

Usage of this method:

override fun onCreate(savedInstanceState: Bundle?) { 
super.onCreate(savedInstanceState)

toast("Now we are talking!", Toast.LENGHT_SHORT)

}

Using Extension function we added an “toast” method to the base “Activity”.

Smart Casting

It’s one of the interesting and sweet little thing by Kotlin Compiler. Let’s head to an example to get the picture.

// Java way
if (view instanceof TextView) {
((TextView) view).setText("So much redundancy");
}
// Kotlin way
if (view is TextView) {
view.setText("So much redundancy"); // Smart Cast
}

The Compiler does smart casting on our behalf. It even handles the negative scenario like if the “view” is not an “TextView”.

Issues

Coming from Java background, it’s difficult writing lambda expressions, static functions, variables and in general the functional stuff in Kotlin but with little practice and little StackOverFlow it can be overcome.

Conclusion

Personally I had an great time with Kotlin especially when I was building my First Kotlin Android app. I hope this article convinces you the need of Kotlin and why we should make our app development better with it.

Kotlin makes Android development a lot more fun again

What’s next

There is a lot yet to cover regarding Kotlin. In the upcoming articles I’ll try to dive deep into setting up Android Studio for Kotlin, writing Android apps, their test cases in Kotlin, more about the features of Kotlin which we discussed earlier and a lot more Kotlin-ized stuff!!

Further links

Lambda functions:
https://en.wikipedia.org/wiki/Anonymous_function
http://stackoverflow.com/questions/16501/what-is-a-lambda-function

Kotlin:
https://kotlinlang.org/
https://blog.aritraroy.in/why-you-should-start-using-kotlin-to-supercharge-your-android-development-in-2017-61db1f11d666#.vubeeeetp
https://www.youtube.com/watch?v=A2LukgT2mKc
https://www.youtube.com/watch?v=mDpnc45WwlI

--

--

Akshay Chordiya
AndroidPub

Google Developer Expert @ Android | Android Engineer @ Clue | Instructor @Caster.IO