Search code examples
kotlinkotlin-extension

How to import type extension function in Kotlin


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?


Solution

  • 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.