下面是一个说明问题的一个小例子:如何从定义类的外部调用扩展方法?
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 }} ...")
}
}
从Java调用扩展方法很简单:
Base o = new Derived();
o.extension("hello world", 'l');
但我无法弄清楚如何做到这一点的纯科特林。 String
和Base
都没有extension
方法。
您可以添加该扩展_functions_也工作。 –
@KirillRakhman,没有明白,你能解释一下吗? – hotkey
我的意思是,不仅可以使用扩展_lambdas_,而且可以使用扩展_functions_来提供隐式接收器。例如:'fun C.inScope()=“”.extended()' –