How to store reified data in instance fields in Kotlin?

I am currently writing DSL for a library, and I would like to supply type metadata using parameters of type reified, for example:

    val config = Config.create()
            .consumerFor<MyType>{
              // consume
            }

My problem is that I can only use the keyword reifiedin inline, and in the function inlineI cannot use instance fields like this:

    inline fun <reified T> consumerFor(consumer: (T) -> Unit) {
        consumers.put(T::class.java, consumer)
        return this
    }

because I get the error message:

The built-in Public-API function cannot access private end users who are not public APIs.

It seems that for now I can not use parameters like reified where they would be most useful. Is there a workaround for this?

+6
source share
2

inline private , , , ( JVM private ).

, internal Kotlin: JVM ( , Java), Kotlin .

internal , . : ()

@PublishedApi:

private val consumers = mutableMapOf<Class<*>, Any>()

@PublishedApi
internal fun <T> putConsumer(clazz: Class<out T>, consumer: (T) -> Unit) {
    consumers.put(clazz, consumer)
}

inline fun <reified T> consumerFor(noinline consumer: (T) -> Unit): C {
    putConsumer(T::class.java, consumer)
    return this
}

, consumers @PublishedApi, :

@PublishedApi
internal val consumers = mutableMapOf<Class<*>, Any>()

inline fun <reified T> consumerFor(noinline consumer: (T) -> Unit): C {
    consumers.put(T::class.java, consumer)
    return this
}
+6

, reified type for, java, - Class<T>.

inline fun <reified T> consumerFor(noinline consumer: (T) -> Unit) =
    consumerFor(T::class.java, consumer)

fun <T> consumerFor(key: Class<T>, consumer: (T) -> Unit) = apply {
    consumers.put(key, consumer)
}

consumers. , - Java.

+1

Source: https://habr.com/ru/post/1015684/


All Articles