kotlin - 如何在 Kotlin 中导入类型扩展函数
问题描述
我为类型编写了一个扩展函数Any
,它将通过名称检索对象属性值。我希望能够在我的项目中的任何地方使用它。这是我的扩展功能:
package com.example.core.utils.validation
import java.util.NoSuchElementException
import kotlin.reflect.full.memberProperties
fun Any.getFieldValue(fieldName: String): Any? {
try {
return this.javaClass.kotlin.memberProperties.first { it.name == fieldName }.get(this)
} catch (e: NoSuchElementException) {
throw NoSuchFieldException(fieldName)
}
}
现在我想像这样使用它
package com.example.core
import com.example.core.utils.validation.*
class App {
val obj = object {
val field = "value"
}
val fieldValue = obj.getFieldValue("field")
}
但是有未解决的参考错误
我应该如何使我的扩展功能全局化并将其导入任何地方?
解决方案
您应该在第二个代码片段中使用import语句而不是第二个包声明。
请参阅文档:https ://kotlinlang.org/docs/reference/extensions.html#scope-of-extensions
实际上我不确定为 Any 类型进行扩展是否有效。我认为在这种情况下,您需要在 Any 类型的对象上调用它。
推荐阅读
- android - 为 RecyclerView 中的偶数项设置背景颜色
- google-dfp - 使用文件加载的内部 gpt 脚本:协议
- python - 如何使用python在线检索信息?
- c - 使二进制文字看起来更清晰的分隔符
- python - 在 Python 3 中,我们如何模拟对对象属性的引用,使其使用尽可能简单和透明?
- python - Cron 没有运行存储在桌面上的 shell 程序
- javascript - JavaScript在递归函数中返回未定义而不是值
- css - 如何修复 ionic 4 和 css 中存在问题的进度条类?
- javascript - js 日期时间正则表达式
- identityserver4 - 如何使用授权码流 + PKCE 从 IdentityServer 获取用户信息?