Writing Kotlin the Kotlin(Non Java) Way

It has been a couple of weeks since I started writing real Kotlin code, and by real Kotlin code I mean going beyond the koans on the Kotlin official website(which are pretty good and you should check them out) to writing libraries and re-writing a few components in my first few weeks as an Android Developer at Shopify.

While I can say that now I am comfortable, enjoying the language and slowly developing an unconditional love for it because it is very easy to pick up new stuff, it really comes to my mind that this speed in learning was not there in the beginning.

This was because of so many reasons, and one of the reasons was the not so clear understanding about the difference between expressions and statements and I am specifically talking about understanding the way this concepts present themeself in Java and Kotlin.

Statements

Putting it in very simple words, when programming or interacting with a computer, a statement is a command that we give to it so that it performs any kind of action/operation.

System.out.println("This is a statement");

The statement above in Java is going to tell the program to print the string to the console and that is the only thing that is going to happen.

This leads us to change our definition of a statement slightly to the following:

An instruction we give to a program that does not return any value and it is always the top level on it’s enclosing block.

Java is a language where pretty much everything is a statement and we instruct our code to do what ever we want by combining different statements together.

Taking a look at a common scenario that we normally do in Android such as putting a String or/and a Parcelable into a Bundle before setting it as an argument to a Fragment we would do it the following way:

Bundle args = new Bundle();
args.putString("key", "value");
args.putParcelable("parcelableKey", pacelableObject);
Fragment fragment = new FragmentX();
fragment.setArguments(args);

Expressions

Expressions are also instructions that we give when writing our programs but they differ from statements because expressions can return values and can be part or take other expressions.

In Java, there are 4 types of expressions:

Assignment expressions: Such as a+=b, or simply a=2
Postfix or infix operations: Such as --a, a++
Methods invocations: calling a method with or no return
Object Creations: Such as new ObjectA()

Moving forward, the above explanation of statements and expressions seems very clear and obvious.

Now, you might be asking yourself how does this relate to writing good Kotlin code?

The answer to that question is that Java has the 4 types of expressions shown earlier in this post, but on the other hand Kotlin was engineered with the heavy use of expressions and functional programming in mind (Checkout a more detailed post by Dan Lew here) as a way to write more concise code.

Writing Kotlin the non Java way at least to the context of this post means understanding that there are expressions almost everywhere in the language .

This means we should try to break free from the Java way of writing multiple statements to using a property of expressions I mentioned earlier that is the ability of combining and be part of other expressions.

Let’s start with the simple example of a function that take an age and checks if the person is old enough to drink(assuming 18 is old enough to drink, at least in some parts of this world).

In Java it would look like this:

public String getDrinkingAuthorization(int age) {
if(age >= 18){
return "Authorized";
}
else{
return "Not Authorized";
}
}

By using the Android Studio “Convert from Java to Kotlin” tool, it would generate the following code:

fun getDrinkAuthorization(age: Int): String{
if(age >= 18){
return "Authorized"
}
else{
return "Not Authorized"
}
}

If you look at the two versions of this function, they definitely look alike and if your desire is to just have your code in a kt file, this should be the moment you pat yourself on the back for writing your first code in Kotlin.

However, I believe that we do what we do out of love; and because of this, we should always strive to improve. The code above can be rewritten the Kotlin Way, were we favor expressions over statements: we take out the repetition of the return keyword from each part of the conditional and use a single return for the entire expression.

That would look like something like this:

fun getDrinkAuthorization(age: Int): String{
return if(age >=18) "Authorized" else "Not Authorized";
}

Note: If you are paying attention, in the snippet above both the if and else don’t have any block body because we only are returning one expression, but if we wanted to do a few more things before returning the value we wanted to, we could provide the expression in a block and the only thing you have to remember is that THE VALUE YOU ARE RETURNING SHOULD ALWAYS BE THE LAST EXPRESSION IN THE BLOCK. Like this:

fun getDrinkAuthorization(age: Int): String{
return if(age >=18){
//..do some funky stuff
"Authorized"
}
else{
//do some funky stuff here too
"Not Authorized"
}
}

Taking the example we used before of the bundle, using the Java to Kotlin converter we will have a code that looks like this:

val bundle = Bundle()
bundle.putString("key", "value")
bundle.putParcelable("parcelableKey", parcelable)
val fragment = FragmentX()
fragment.arguments = bundle

By taking advantage of expressions in Kotlin, we can write this code in many different forms. Below is one of the ways in which we can write this code:

val fragment = TestFragment().apply {
arguments = Bundle().apply{
this
.putString("Key","value")
this.putParcelable("parcelableKey", parcelable)
}
}

The code snippet above uses one of the Kotlin standard library functions.

The apply function which basically can be applied to any object and what it does is to pass the calling object to the block body that can be accessed with the this keyword and returns an object of the same type of the calling object after the operation done inside the block.

This is another topic that I will not go into much details as there is this great post by Tomek Polański that can be found here.

Conclusion

The Java to Kotlin converter is a great way to start moving your codebase to Kotlin, but understanding the simple concepts such as the difference between an Expression and a Statement can help you write better Kotlin code in the long run.

Things such as the Standard library functions are not very intuitive in the beginning.

I would advise you to first write the code the java way and keep experimenting and learning with new functions until you get your desired results.

Thanks for reading some of the notes I have been taking during my journey learning Kotlin.
Please feel free to drop your thoughts or questions in the comments section. Let’s keep the conversation going and learn together.
If you find this post interesting, share with your friends, co-workers and show some love recommending it by clicking on the green little heart =)

Thanks to @FranciscoCavedon, Rebecca Franks and Rosário Pereira Fernandes for taking time to help me review this post.

See you next time,

DM