> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gorules.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Kotlin Rules Engine

> Integrate GoRules into your Kotlin application.

Install the ZEN Engine and evaluate your first decision in Kotlin.

## Installation

```kotlin theme={null}
dependencies {
    implementation("io.gorules:zen-engine-kotlin:2.0.0")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
}
```

## Basic usage

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.ZenEngine
import io.gorules.zen_engine.kotlin.JsonBuffer
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val ruleJson = object {}.javaClass.getResourceAsStream("/rules/pricing.json")!!.readBytes()

    ZenEngine(null, null).use { engine ->
        val decision = engine.createDecision(JsonBuffer(ruleJson))

        val input = JsonBuffer("""
            {
                "customer": { "tier": "gold", "yearsActive": 3 },
                "order": { "subtotal": 150, "items": 5 }
            }
        """)

        val response = decision.evaluate(input, null)

        println(response.result)
        // => {"discount":0.15,"freeShipping":true}
    }
}
```

## Loader

`ZenEngine` accepts an optional `ZenLoader` that serves decisions by key. Use `Static`, `Filesystem`, or `Zip` for common backends, or `Callback` for custom loading logic.

### Static

Register decisions in memory. Use this when your rules ship with the application or are already loaded:

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.ZenEngine
import io.gorules.zen_engine.kotlin.ZenLoader
import io.gorules.zen_engine.kotlin.JsonBuffer
import java.nio.file.Files
import java.nio.file.Path
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val pricing = Files.readString(Path.of("./rules/pricing.json"))

    val loader = ZenLoader.Static(mapOf("pricing.json" to JsonBuffer(pricing)))

    ZenEngine(loader, null).use { engine ->
        val response = engine.evaluate("pricing.json", JsonBuffer("""{ "amount": 100 }"""), null)
        println(response.result)
    }
}
```

### File system

Load decisions from files under a root directory. Keys resolve to paths relative to the root:

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.ZenEngine
import io.gorules.zen_engine.kotlin.ZenLoader
import io.gorules.zen_engine.kotlin.JsonBuffer
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val loader = ZenLoader.Filesystem("./rules")

    ZenEngine(loader, null).use { engine ->
        val response = engine.evaluate("pricing.json", JsonBuffer("""{ "amount": 100 }"""), null)
        println(response.result)
    }
}
```

### Zip archive

Pass the bytes of a zip archive. Every `.json` entry becomes a decision keyed by its path within the archive. This pairs naturally with BRMS release ZIPs - download the release from object storage and hand the bytes to the engine:

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.ZenEngine
import io.gorules.zen_engine.kotlin.ZenLoader
import io.gorules.zen_engine.kotlin.JsonBuffer
import software.amazon.awssdk.regions.Region
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.s3.model.GetObjectRequest
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val s3 = S3Client.builder().region(Region.US_EAST_1).build()
    val request = GetObjectRequest.builder()
        .bucket("my-rules-bucket")
        .key("decisions.zip")
        .build()
    val zipBytes = s3.getObjectAsBytes(request).asByteArray()

    ZenEngine(ZenLoader.Zip(zipBytes), null).use { engine ->
        val response = engine.evaluate("pricing.json", JsonBuffer("""{ "amount": 100 }"""), null)
        println(response.result)
    }
}
```

### Custom loader

For any other backend, implement `ZenDecisionLoaderCallback` and wrap it in `ZenLoader.Callback`:

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.ZenEngine
import io.gorules.zen_engine.kotlin.ZenLoader
import io.gorules.zen_engine.kotlin.ZenDecisionLoaderCallback
import io.gorules.zen_engine.kotlin.JsonBuffer
import java.nio.file.Files
import java.nio.file.Path
import kotlinx.coroutines.runBlocking

val callback = object : ZenDecisionLoaderCallback {
    override suspend fun load(key: String): JsonBuffer? {
        val path = Path.of("./rules", key)
        if (!Files.exists(path)) return null
        return JsonBuffer(Files.readAllBytes(path))
    }
}

fun main() = runBlocking {
    ZenEngine(ZenLoader.Callback(callback), null).use { engine ->
        val response = engine.evaluate("pricing.json", JsonBuffer("""{ "amount": 100 }"""), null)
        println(response.result)
    }
}
```

Returning `null` from the callback reports the key as not found.

## Batch evaluation

Evaluate many requests in one call. Each result reports its own success or failure, so one bad input never fails the batch:

```kotlin theme={null}
val results = engine.evaluateBatch(
    listOf(
        ZenBatchRequest("pricing.json", JsonBuffer("""{ "amount": 100 }""")),
        ZenBatchRequest("pricing.json", JsonBuffer("""{ "amount": 250 }""")),
        ZenBatchRequest("eligibility.json", JsonBuffer("""{ "age": 30 }"""))
    ),
    null
)

for (result in results) {
    if (result.success) {
        println(result.data?.result)
    } else {
        println("Evaluation failed: ${result.error}")
    }
}
```

## Coroutines

Evaluation functions are `suspend` functions, integrating natively with Kotlin coroutines:

```kotlin theme={null}
import kotlinx.coroutines.*

coroutineScope {
    val results = inputs.map { input ->
        async {
            decision.evaluate(JsonBuffer(input), null)
        }
    }.awaitAll()

    results.forEach { println(it.result) }
}
```

## Error handling

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.ZenException

try {
    val response = decision.evaluate(input, null)
    println(response.result)
} catch (e: ZenException) {
    println("Evaluation failed: ${e.message}")
}
```

## Tracing

Enable tracing to inspect decision execution:

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.ZenEvaluateOptions

val options = ZenEvaluateOptions(trace = true, maxDepth = null)

val response = decision.evaluate(input, options)

println(response.trace)
// Each node's input, output, and performance timing

println(response.performance)
// Total evaluation time
```

## Expression utilities

Evaluate ZEN expressions outside of a decision context:

```kotlin theme={null}
import io.gorules.zen_engine.kotlin.evaluateExpression
import io.gorules.zen_engine.kotlin.evaluateUnaryExpression
import io.gorules.zen_engine.kotlin.JsonBuffer

// Standard expressions
val result = evaluateExpression("a + b", JsonBuffer("""{ "a": 5, "b": 3 }"""))
// => 8

val total = evaluateExpression("sum(items)", JsonBuffer("""{ "items": [1, 2, 3, 4] }"""))
// => 10

// Unary expressions (comparison against $)
val isValid = evaluateUnaryExpression(">= 5", JsonBuffer("""{ "$": 10 }"""))
// => true

val inList = evaluateUnaryExpression("'US', 'CA', 'MX'", JsonBuffer("""{ "$": "US" }"""))
// => true
```

## Performance note

> [!NOTE]
>
> The Kotlin bindings use JNA (Java Native Access) for interoperability with the native Rust engine. This introduces some overhead compared to native Rust or direct bindings. We plan to revisit this when the FFM (Foreign Function & Memory) API becomes more widely adopted.

## Best practices

**Use `.use {}` for resource management.** `ZenEngine` implements `AutoCloseable` to release native resources.

```kotlin theme={null}
ZenEngine(null, null).use { engine ->
    // use engine
}
```

**Initialize the engine once.** Create a single `ZenEngine` instance at application startup and reuse it for all evaluations.

**Prefer declarative loaders.** `ZenLoader.Static`, `ZenLoader.Filesystem`, and `ZenLoader.Zip` serve decisions from native code without callback overhead. Reserve `ZenLoader.Callback` for backends the built-in variants don't cover.

**Leverage coroutines for parallel evaluation.** Use `async`/`awaitAll` to evaluate multiple decisions concurrently.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.