pkl-config-kotlin Library

The pkl-config-kotlin library extends pkl-config-java with Kotlin specific extension methods and object converters. We recommend that Kotlin projects depend on this library instead of pkl-config-java.

Installation

The pkl-config-kotlin library is available from Maven Central. It requires Java 11 or higher and Kotlin 1.5 or higher.

Gradle

To use the library in a Gradle project, declare the following dependency:

  • Kotlin

  • Groovy

build.gradle.kts
dependencies {
  implementation("org.pkl-lang:pkl-config-kotlin:0.25.3")
}

repositories {
  mavenCentral()
}
build.gradle
dependencies {
  implementation "org.pkl-lang:pkl-config-kotlin:0.25.3"
}

repositories {
  mavenCentral()
}

Maven

To use the library in a Maven project, declare the following dependency:

pom.xml
<project>
  <dependency>
    <groupId>org.pkl-lang</groupId>
    <artifactId>pkl-config-kotlin</artifactId>
    <version>0.25.3</version>
  </dependency>
</project>

Usage

Below is the Kotlin version of the Java ConfigEvaluator example. Differences to the Java version are called out.

val evaluator = ConfigEvaluator.preconfigured().forKotlin() (1)
val config = evaluator.use { (2)
  it.evaluateText("""pigeon { age = 5; diet = "Seeds" }""")
}
val pigeon = config["pigeon"] (3)
val age = pigeon["age"].to<Int>() (4)
val hobbies = pigeon["diet"].to<List<String>>() (5)
1 Use the forKotlin() method to preconfigure the builder with Kotlin specific conversions. In particular, forKotlin() eliminates the need to annotate constructor parameters of Kotlin classes and Kotlin data classes with @Named.
2 The evaluator should be closed once it is no longer needed. Here this is done with a Kotlin use {} expression. Any data returned by the evaluator before calling close() remains valid.
3 Navigate to the "pigeon" child. The subscript notation is shorthand for config.get("pigeon").
4 Convert "age" to Int with the Config.to() extension method. The target type is provided as a type argument. Always use Config.to() instead of Config.as() in Kotlin.
5 Config.to() makes conversions to parameterized types straightforward: to<List<String>>() instead of as(JavaType.listOf(String::class.java)).

For properties that are allowed to be null, convert to a nullable type:

val evaluator = ConfigEvaluator.preconfigured().forKotlin()
val config = evaluator.use {
  it.evaluateText("name = null") (1)
}
val name = config["name"].to<String?>() (2)
1 To indicate that null is an allowed value, convert to the nullable type String?. Converting to String would result in a ConversionException.

For a ready-to-go example with full source code, see config-kotlin in the pkl/pkl-examples repository.

Further Information

Refer to the Javadoc and sources published with the library, or browse the library’s main and test sources.