如何从具有相同签名的方法或扩展函数中调用顶级函数? [英] How to call a toplevel function from a method or an extension function of the same signature?

查看:73
本文介绍了如何从具有相同签名的方法或扩展函数中调用顶级函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用kotlin 1.1.2-2

I use kotlin 1.1.2-2

我想从方法Mul2.plus100(Int):Int调用顶级函数plus100(Int):Int.我尝试在下面的代码中执行此操作,但实际上Mul2.plus100本身被调用.

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
}

反正可以从Mul2.plus100访问plus100吗?

推荐答案

您可以使用函数所在的包来引用它:

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)
}

您还可以使用import as重命名该函数-如果它来自另一个文件或软件包,则更有意义,但也可以在单个文件中使用:

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)
}

这篇关于如何从具有相同签名的方法或扩展函数中调用顶级函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆