Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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?

like image 838
letrec Avatar asked Jul 12 '17 13:07

letrec


1 Answers

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)
}
like image 159
zsmb13 Avatar answered Oct 22 '22 10:10

zsmb13