MoMo
MoMo

Reputation: 186

Accessing static extension function from another class in Kotlin?

Let's say we have the following extension function:

class Helper {
  companion object {
    fun Int.plus(value: String) = Integer.valueOf(value).plus(this)
  }

}

How can you access the plus extension function from the Helper class in another class. Is there a way where we can do something like this for instance:

class OtherClass {
  fun someMethod() {
    val eight = 7.Helper.Companion.plus("1")
  }

}

Upvotes: 2

Views: 920

Answers (2)

voddan
voddan

Reputation: 33829

In your example Int.plus(value: String) is a member function of the Helper.Companion object (the fact that it is a companion object or that it is inside another class does not matter). This case is described in the Declaring Extensions as Members section of the documentation.

In short, to access a function with two receivers (an extension receiver of type Int and a dispatch receiver of type Helper.Companion) you have to have them both in the scope.

This can be achieved in a number of ways:

with(Helper.Companion) {
    239.plus("")
}

or

with(Helper.Companion) {
    with(239) {
        plus("")
    }
}

P.S. Putting an extension function into a companion object is very irregular and not idiomatic. I can hardly imagine why you would need that.

Upvotes: 5

zsmb13
zsmb13

Reputation: 89648

An extension declared like this is a member extension function, and is only going to be visible within the Helper class. If you need to access it outside of that class, put it in a wider scope, for example, make it a top level function. Alternatively, you could make it a regular function that takes two parameters, if you want to keep it within a class.


As an additional hint, you can mark this function an operator if you want to use it with the + symbol:

operator fun Int.plus(value: String) = Integer.valueOf(value) + this

val x = 2 + "25"

Upvotes: 3

Related Questions