letrec
letrec

Reputation: 559

How to call a toplevel function from a method or an extension function of the same signature?

I use kotlin 1.1.2-2

I want to call top-level function plus100(Int):Int from method Mul2.plus100(Int):Int. I tried to do this in the following code but actually Mul2.plus100 itself is called.

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 anyway to access plus100 from Mul2.plus100?

Upvotes: 7

Views: 1915

Answers (1)

zsmb13
zsmb13

Reputation: 89578

You can use the package the function is in to refer to 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 an import as - this makes more sense if it's coming from another file or package, but works within a single file too:

package pckg

import pckg.plus100 as p100

fun plus100(v: Int): Int = v + 100

class Mul2 {
    fun plus100(v: Int): Int = p100(2 * v)
}

Upvotes: 11

Related Questions