Kotlin: Extension Function — Hax

MJ Manaog
2 min readJul 9, 2020

If you want your utility/helper method to be like one of a property/method of the built-in classes, you can use this hax called extension function.

The typical way of creating a helper:

  • We’ve created a new object DateTimeHelper, added a public method that converts your date and time to duration.
  • Then you’ll have to call this like DateTimeHelper.dateDuration(myStringDate) to get the result.

Another way to do this using an extension function:

  • Line 14 — this is how to create an extension function. What we’re saying in Line 14 is that we want to associate this function with the String class, but we’re not actually adding this method to the built-in String class (we can’t really do that) rather we’re just creating an illusion.
  • Line 16 — if you take a look at our implementation in the DateTimeHelper.kt we have a parameter date but in our extension function, we don’t but instead, we used this, that’s because we’re going to call this function using a String instance just like .toUpperCase() .
  • Line 11 — that’s how we call the DateTimeHelper object and its method dateDuration(date:String)
  • Line 12 — this is how we easily call our created extension functiondateDuration as if it is a part of a String class.

Output: 169 day(s) ago 🐱👌🏻

You can use other types like Int, Boolean, Double, and etc. You can also have a separate file for the extension functions you made as long as it is in the top-level of the file.

Thanks :D

--

--