首页 > 解决方案 > 如何在 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")
}

但是有未解决的参考错误

我应该如何使我的扩展功能全局化并将其导入任何地方?

标签: kotlinkotlin-extension

解决方案


您应该在第二个代码片段中使用import语句而不是第二个声明。

请参阅文档:https ://kotlinlang.org/docs/reference/extensions.html#scope-of-extensions

实际上我不确定为 Any 类型进行扩展是否有效。我认为在这种情况下,您需要在 Any 类型的对象上调用它。


推荐阅读