Kotlin调用成员其他类的扩展功能 [英] Kotlin call member Extension function from other class
问题描述
我想在多个类中使用此功能:
I would like to use this function in multiple classes:
fun <T> T?.ifNull(function: (T?, s:String) -> Unit) {
}
我该怎么做?
这就是我想使用它的方式:
This is how I would like to use it:
class A{
fun <T> T?.ifNull(function: (T?, s:String) -> Unit) {
}
}
class B{
constructor(){
val a = A()
//I want to use the function here
}}
推荐答案
如果将扩展功能定义为类A
的成员,则该扩展功能仅在A
的上下文中可用.也就是说,您当然可以直接在A
内部使用它.但是,从另一个类B
来看,它不是直接可见的. Kotlin具有所谓的范围函数,例如with
,可用于将您的类带入A
的范围.以下内容演示了如何在B
内部调用扩展函数:
If you define an extension function as a member of a class A
, that extension function is only usable in the context of A
. That means, you can use it inside A
directly, of course. From another class B
though, it's not directly visible. Kotlin has so called scope functions like with
, which may be used for bringing your class into the scope of A
. The following demonstrates how the extension function is called inside B
:
class B {
init {
with(A()) {
"anything".ifNull { it, s -> }
}
}
}
作为一种替代方法(通常是推荐的方法),您可以在顶级(即直接在文件中)定义扩展功能:
As an alternative, and this is mostly the recommended approach, you would define extension functions top-level, i.e. in a file directly:
fun <T> T?.ifNull(function: (T?, s: String) -> Unit) {
}
class A {
init {
"anythingA".ifNull { it, s -> }
}
}
class B {
init {
"anythingB".ifNull { it, s -> }
}
}
这篇关于Kotlin调用成员其他类的扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!