Skip to content
zml edited this page Nov 14, 2020 · 6 revisions

As of version 3.7, Configurate provides several extensions to improve integration with Kotlin.

Setup

In Gradle:

dependencies {
    implementation("org.spongepowered:configurate-extra-kotlin:4.0.0")
}

In Maven:

<dependencies>
    <!-- ... -->
    <dependency>
        <groupId>org.spongepowered</groupId>
        <artifactId>configurate-extra-kotlin</artifactId>
        <verison>4.0.0</version>
    </dependency>
    <!-- ... -->
</dependencies>

General

To interact more easily with mapped types, there are extensions using reified type parameters to generate the appropriate type token: node.get<T>(default: T? = null) and node.set<T>(value: T), and extensions using KClass<T> rather than Java's Class to remove some of the interoperability friction

Object Mapping

The T.mapper() extension function allows accessing an ObjectMapper built for any object type, and the function objectMapper<T>() allows accessing object mappers constructed for a specific generic type on the default object mapper factory. ObjectMapperFactory.getMapper<T>() and TypeSerializerCollection.get<T>() both allow accessing their respective types by using generic types, rather than explicit TypeTokens.

since 4.0: Kotlin extras adds support for using data classes with the ObjectMapper, as long as kotlin-reflect is available. The mapper factory returned by the extension functions in the extra-kotlin module is already configured to use this. When using other ways of accessing node values, you'll want to configure this yourself:

    return YamlConfigurationLoader.builder()
        .path(source)
        .defaultOptions {
            it.serializers { s ->
                s.registerAnnotatedObjects(
                    ObjectMapper.factoryBuilder()
                        .addDiscoverer(dataClassFieldDiscoverer())
                        .build()
                )
            }
        }
        .build()

kotlinx.serialization

While Configurate does not directly provide support for kotlinx.serialization, there is a community project at ItsDoot/configurate-serialization that can currently deserialize a node into a Kotlin Serializable object.

Flows

With Configurate's Publisher API used for file and value watchers, listeners are able to be converted into Kotlin's Flows for better integration with Kotlin's coroutine concurrency.

Clone this wiki locally