Reputation: 79
I wrote an extension function for Any
type, that will retrieve object property value by its name. I want to be able to use it from everywhere in my project. Here is my extension function:
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)
}
}
Now I want to use it like this
package com.example.core
import com.example.core.utils.validation.*
class App {
val obj = object {
val field = "value"
}
val fieldValue = obj.getFieldValue("field")
}
But there is Unresolved reference error
How should I make my extension function global and import it anywhere?
Upvotes: 3
Views: 8883
Reputation: 507
You should use import statement instead of second package declaration in your second code snippet.
See documentation: https://kotlinlang.org/docs/reference/extensions.html#scope-of-extensions
And actually I am not sure that it is valid to make extension for Any type. I think in that case you need to call it on object of type Any.
Upvotes: 7