How do I call a top-level function from a method or extension function of the same signature?
I am using kotlin 1.1.2-2
I want to call a top level function plus100(Int):Int
from a method Mul2.plus100(Int):Int
. I tried to do it in the following code, but it actually gets called itself Mul2.plus100
.
class Mul2 {
fun plus100(v: Int): Int = plus100(2 * v)
}
fun plus100(v: Int): Int = v + 100
fun main(args: Array<String>) {
val v = Mul2()
println(v.plus100(10)) // expected: "120", actual: StackOverflowError
}
Is there any access to plus100
from Mul2.plus100
?
+3
source to share
1 answer
You can use the package the function is in to reference it:
package pckg
fun plus100(v: Int): Int = v + 100
class Mul2 {
fun plus100(v: Int): Int = pckg.plus100(2 * v)
}
You can also rename the function with import as
- this makes sense if it comes from a different file or package, but also works in the same file:
package pckg
import pckg.plus100 as p100
fun plus100(v: Int): Int = v + 100
class Mul2 {
fun plus100(v: Int): Int = p100(2 * v)
}
+4
source to share