You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否无需导入即可调用其他包中的Kotlin扩展函数?

是否可以不导入就调用其他包中的Kotlin扩展函数?

给定如下扩展函数:

package ext
fun Int.plusOne() = this + 1

有没有办法不先导入该函数就直接调用它?

我可以无需导入调用非扩展函数(忽略该函数无需导入的情况,仅关注语法有效性):

val el: List<Int> = kotlin.emptyList()

也可以无需导入实例化类:

val str = java.lang.String("yo.")

但我尚未找到扩展函数的等效调用方式(我知道以下示例有些不合理):

val i = 42
// 以下均为无效语法...

i.ext.plusOne()

ext.plusOne(i)

i.(ext.plusOne)()

i.(ext.plusOne())

ext.i.plusOne()

val pO = ext.plusOne
i.pO()

附加问题:扩展属性是否也存在同样的情况?

补充说明:在扩展接收者隐式存在的场景下,同样不允许使用全限定名调用:

// 有效写法:
import ext.plusOne
val four = with(3) { plusOne() }

// 无法解析引用:
val four = with(3) { ext.plusOne() }

内容的提问来源于stack exchange,提问作者Kolja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 04:18:21