How can I create an extension function on System class?

502 Views Asked by At

I am trying to create an extension function on java.lang.System to refactor currentTimeMillis usage to the following System.currentTimeinSeconds() extension method that returns a String. (This is done to avoid duplicate code and to reuse it in the code)

This is what I have tried but its not working:

fun System.currentTimeInSeconds () : String {
    return ((this.currentTimeMillis / 1000).toString()) 

Any guidance as to why this is not working? Thanks.

3

There are 3 best solutions below

0
Louis Wasserman On

You cannot do this. Kotlin currently only supports extension functions on objects, not classes, and System is a class.

0
u-ways On

Welcome to SO, first, it's important to reiterate the difference between a class and an object:

  • A class is a blueprint or a template for creating objects. It defines the properties and behaviour of objects.
  • On the other hand, an object is an instance of a class. It is created using the blueprint or template provided by the class.

Now that's out of the way, you can find decent amount of information of Kotlin Extension functions here:

The documentation states:

you can write new functions for a class or an interface from a third-party library that you can't modify. Such functions can be called in the usual way, as if they were methods of the original class. This mechanism is called an extension function. There are also extension properties that let you define new properties for existing classes.

And if you further looked down:

The this keyword inside an extension function corresponds to the receiver object (the one that is passed before the dot). Now, you can call such a function on any MutableList:

So the extension function acts on a received object, not the blueprint (class) itself.

System is a class and the currentTimeMillis() is a static native method. Therefore, when you try to create an extension function for it, your extension function will be called on the class itself, not on an object of the class in your case as you were calling the static method all along from System.

Next, does your requirements really need an extension function for this? You're calling a static, creating a function should be enough. (i.e. You have all the information you need)

fun stringifedTimeInSeconds() =
    System.currentTimeMillis().div(1000).toString()

Finally, it might be worth reading some answers in the following question:

Hope this helps.

0
Tobse On

By the way, there is a proposal in the official Kotlin Evolution and Enhancement Process (KEEP) for this.
You can check out the details in Kotlin statics and static extensions.
But unfortunately we won't see any progress in the near feature, because the proposal was removed from the current roadmap.

Removed Item https://kotlinlang.org/docs/roadmap.html#new-items