Leveraging the power of functions in Kotlin

Harshit Dwivedi
Jan 29, 2018 · 4 min read

Are you still creating Utility class in your apps? #9 will shock you!

One might think, how can writing something as trivial as a function be optimized with Kotlin!?

But worry not my friend, Kotlin has something amazing for you in store.

1. Let’s start with something very basic, i.e. overloading functions.
Say I have to create an overloaded funtion that can take in a max of 6 and min 2 parameters.

Using Java, this requires us to create 6 different methods which seems very impractical and repetitive.
With Kotlin, we have something known as default values, which automatically handles this for us.

So something like :

fun createStudent(name: String,
course: String,
age: Int = 0,
address: String = "",
email: String = "",
linkedIn: String = ""): Student =
Student(name, course, age, address, email, linkedIn)

Will allow us to call this method as :

createStudent(“name”,”Course”), 
createStudent(“name”,”Course”,22), createStudent(“name”,”Course”,address=”Address”, email=”test@example.com”),
...

Do note that if we plan on having only seleted arguments while calling the functions which may not be in order, we can pass the arguments as named arguments which allows Kotlin to automatically infer the correct argument for us.
It’s also worthwhile to note that specifying name for a particular argument will result in us specifying the names for all the arguments after that so as to avoid confusion.

NOTE : While calling this method from a Java file, this overloading won’t work out of the box.
We need to annotate the method with a special annotation @JvmOverloads, which will create the overloaded methods in java for us.

You can also check the decompiled bytecode to see what all methods are generated for us when using @JvmOverloads annotation.

Kotlin automatically generates all the possible combinations for us here

2. Next up, we have something very common, static Utility classes.
Often methods which are not specific to any particular android class end up in the static Utility class so that they can be accessed conveniently.

With Kotlin, we have something known as top-level functions and top-level properties.
Instead of creating meaningless classes which wrap these methods, we can simply declare our functios directly outside of our parent class and that’s it!
Such methods will be accessible from anywhere in our package.

Going where no Java developer has gone before!

If we go ahead and decompile this, Kotlin code, it’s nothing magical.
Kotlin internally places these methods in a Static class for us :

Note the Name of this static class depends on the original class, my method was a part of

3. Last but not the least, extension functions!
Let’s think about a very basic use case, Toasts.
Wouldn’t it be nice if we had something like this :

“I’m a long toast”.longToast(context)

Instead of calling the Toast we love and know, again and again

Toast.makeText(context,”I’m a long toast”,Toast.LENGTH_LONG).show()

With Kotlin, this is quite possible, thanks to the awesome Extension Functions that can be called by objects of a particular class, without being defined in that class.

How can we do this? Well, pretty easily!

Let’s take a look at the components involved here :

1. Any.shortToast() : Here, Any is the Receiver Type, which is the type on which the extension funnction is defined.
In Kotlin, Any is anologus to Object class in Java, Any.shortToast() means that my shortToast method can be called on every object available.

2. this.toString() : this here is the Receiver Object, i.e. an instance of the Receiver Type.

So when I write something like this :

4.shortToast(context)

Here, the Receiver Type here is Int, whereas the Receiver object is 4.

Pretty cool, isn’t it!?

But, before you go ahead and accept this as Voodoo magic, we need to realize that unnder the hood, this is Plain Java code that runs on our phones.
It’s a good practice to know, how exactly this works.

Taking a look at the compiled Java Bytecode, we can see that a new Java class named ExtensionFuncKt.java is created which has a static method.

This method also takes in a Receiver and a Context and shows the Toast accordingly.

I hope that with this article, you got a good overview at some of the more language specific features of Kotlin that help set it apart from Java.
You can start to see, that by using Kotlin effectively not only we can leverage a more powerful set of APIs, but we also can let Kotlin take care of repetitive housekeeping tasks for us!

That’s it! I hope you liked this post. If you did, don’t forget to 👏.

Till next time!

Have feedback? Let’s connect on Twitter.

Coding Blocks

Daily Tidbits on Android, Javascript and Machine Learning

Harshit Dwivedi

Written by

Has an *approximate* knowledge of many things. harshithd.com

Coding Blocks

Daily Tidbits on Android, Javascript and Machine Learning

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade