下面是一個說明問題的一個小例子:如何從定義類的外部調用擴展方法?
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()' –