下面是一个简单的例子来说明这个问题:

abstract class Base {
    abstract fun String.extension(x: Char)
}

class Derived : Base() {
    override fun String.extension(x: Char) {
        // Calling lots of methods on String, hence extension method
        println("${first()} $length ${last()} ${firstOrNull { it == x }} ...")
    }
}

Calling the extension method from Java is trivial:

Base o = new Derived();
o.extension("hello world", 'l');

但我不知道如何在纯Kotlin 做到这一点.StringBase似乎都没有extension方法.

推荐答案

首先,请注意,定义为成员的扩展函数需要两个接收器,一个是封闭类的实例(dispatch receiver,通常是封闭类的this),另一个是函数扩展的类型的实例(extension receiver).这是here条记录.

所以,要从类外调用这样的函数,必须提供两个接收器.Kotlin doesn't have any syntax可以像(x, "abc").stringExtension()那样显式地实现这一点,但您可以使用extension lambda隐式地提供调度接收器:

class C(val name: String) {
    fun String.extended() = this + " extended by " + name
}

fun main(args: Array<String>) {
    val c = C("c")
    with(c) { println("abc".extended()) }
}

(runnable demo of this code)

In the with(...) { ... } block, c becomes the implicit receiver, thus allowing you to use it as a dispatch receiver in C member extensions. This would work with any other function that uses functional types with receivers: apply, run, use etc.

In your case, it would be with(o) { "hello world".extension('l') }

@KirillRakhman所述,C的扩展函数的扩展接收器也可以隐式地用作C中定义的扩展的调度接收器:

fun C.someExtension() = "something".extended()

Kotlin相关问答推荐

了解Kotlin函数

有什么原因,我得到一个空相关的错误在这个代码

"Kotlin中的表达式

如何定义一个函数来接受任何具有特定字段的数据类

Rabin-Karp字符串匹配的实现(Rolling hash)

如何将光标从一个文本字段传递到 Jetpack Compose 中的其他文本字段?

为什么这个 Kotlin 代码不起作用? (如果 str[index] 在列表中,则打印)

在 kotlin 中重载函数时,我在一些非常基本的代码上不断收到类型不匹配

即使 Kotlin 的 `Map` 不是 `Iterable`,它如何以及为什么是可迭代的?

伴随对象在变量更改时更改它的值

在 kotlin 中写入 parcer 可空值

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

如何处理 Kotlin 中的异常?

使用kotlinx协同程序测试中的类时出错

从 Spring WebFlux 返回 Flux 返回一个字符串而不是 JSON 中的字符串数组

Kotlin not nullable值可以为null吗?

大小写敏感性 Kotlin / ignoreCase

如何在Kotlin中创建无限长的序列

比较Kotlin的NaN

如何在 Kotlin 中生成 MD5 哈希?