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

# Kotlin

> Call an app from Kotlin on the JVM or Android with a client generated from its contract

The Kotlin client runs an app's queries and mutations from the JVM or Android.
`bijection client kotlin` generates a typed package from the app's contract;
it depends on the runtime `com.bijection:client-kotlin`.

## Install

Add the runtime and your generated package to the build:

```kotlin build.gradle.kts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
dependencies {
    implementation("com.bijection:client-kotlin:0.10.0")
    implementation(project(":orders-client"))
}
```

The runtime needs `kotlinx-coroutines-core` and nothing else.

## Generate a client

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection client kotlin --out orders-client --name com.acme.orders
```

The command reads the committed `bijection.lock` and refuses when its
`contract` line differs from the source's: run `bijection check --write-lock`
and commit the lock first. The package holds:

| File | Holds |
| - | - |
| `App.kt` | `CONTRACT`, a `connect` that pins it, and `object App`: the exposed tree, one ref per function at its path. |
| `Types.kt` | A data class for each argument and value object, and an enum class for each set of string literals, each with its codecs. |
| `interface.json` | The language-neutral interface document. |

Regenerate whenever the lock changes.

## Connect

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import com.acme.orders.App
import com.acme.orders.connect
import com.bijection.client.ConnectOptions

val client = connect("https://acme.bijection.app", ConnectOptions(token = token))
```

`token` is a fixed credential; pass `tokenSource` instead to be asked on every
request (`TokenSource { refresh -> session.token(refresh) }`). Leave both out to
call anonymously. The generated `connect` pins `CONTRACT`. An installation whose
contract differs refuses every call with `Conflict`, and the message starts
with `ContractStale`.

For a dynamic tool, pass `ConnectOptions(discover = true)` to the raw connector. A pinned client refuses a path absent from its contract map before sending it.

## Calls

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
val listed = client.query(App.notes.list, Unit)
val placed = client.mutate(App.orders.place, OrdersPlaceArgs(sku = "A-1", quantity = 2))
```

A function is addressed by its tree path: `App.orders.place` is `place` in the
`orders` module. A function without arguments takes `Unit`.

`mutate` takes `once`, the identity of one logical mutation. The same `once` and
arguments answer the original result; the same `once` with other arguments
refuses `Invalid`. Without one, the client mints one for the call. A result
`Unknown` means it may have happened: ask again with the same `once`.
An uncertain mutation carries its original request key in `Refusal.once`.

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
val once = UUID.randomUUID().toString()
var result = client.mutate(App.orders.place, args, once = once)
while (result is Result.Refusal && result.code == HostCode.UNKNOWN) {
    delay(1_000)
    result = client.mutate(App.orders.place, args, once = once)
}
```

## Frames

Each frame method returns a new client; the original is unchanged and both
share one connection.

| Method | Frame field | Takes |
| - | - | - |
| ``client.`as`(principal)`` | `as` | A principal id such as `person:alice` (operator credentials only). |
| `client.under(label)` | `under` | `Label.tag("access.finance")`, `Label.member("access.tenant", "acme")`, joined with `and`, or `Label.anyOf(...)`. |
| ``client.`in`(world)`` | `in` | `World.version(v)` or `World.branch(b)`. |
| `client.at(instant)` | `at` | A `java.time.Instant`, the valid instant. |

A committed mutation's result carries its `version`. Pass it as `seen` to read
your own write:

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
val placed = client.mutate(App.orders.place, args)
if (placed is Result.Ok) client.query(App.orders.recent, OrdersRecentArgs(customer), seen = placed.version)
```

## Results

Every call answers a `Result`: `Result.Ok(value, version)` or
`Result.Refusal(code, message, guard)`. It never throws for a refusal.

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
when (val result = client.mutate(App.orders.cancel, OrdersCancelArgs(order))) {
    is Result.Ok -> println("cancelled")
    is Result.Refusal -> when (result.code) {
        "OutOfStock" -> println(result.message)
        HostCode.FORBIDDEN -> println("refused by ${result.guard}")
        else -> println("${result.code}: ${result.message}")
    }
}
```

`code` is one of the twelve host codes (`HostCode.UNKNOWN`, `DISALLOWED`,
`FORBIDDEN`, `INVALID`, `ABSENT`, `EXISTS`, `CONFLICT`, `ERASED`, `EXPIRED`,
`WITHDRAWN`, `LIMIT`, `FAILED`) or one of the codes the function declares in
`refuses`, exactly as it refused. Any other code from the host is folded into
its host code, with the original code as `reason`. A host code's `reason` is
its precise cause (`BudgetExhausted` under `Limit`), or null; `message` never
starts with the code or the reason. On `Forbidden`, `guard` is the path of the
guard that refused.

## Watch

`watch` returns a `Flow` of results: the current value, then each change. The
watch stops when collection ends.

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
client.watch(App.notes.list, Unit).collect { listed ->
    if (listed is Result.Ok) render(listed.value)
}
```

A client with `in` or `at` answers once. The JVM opens an HTTP event stream.
On Android, pass a `LiveFactory` over your HTTP library as `ConnectOptions(live = ...)`.

## Trial

`trial` runs a call in a discarded world and commits nothing:

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
val trial = client.trial(App.orders.place, args)
trial.writes.forEach { println("${it.verb} ${it.table} ${it.key}") }
trial.tasks.forEach { println("would submit ${it.target}") }
```

`trial.result` is how the call would have ended; a guard's refusal carries
`guard`. `trial.validUntil` is the instant the answer is valid until (a call at
the same version committed before it is decided the same way), or null when
nothing time-dependent bounds it.

## Values

| Bijection type | Kotlin type |
| - | - |
| `t.string`, keys, versions | `String` |
| `t.number` | `Double` |
| `t.int` | `Long` |
| `t.boolean` | `Boolean` |
| `t.bytes` | `ByteArray` |
| `Decimal` | `java.math.BigDecimal` |
| `t.date` | `java.time.LocalDate` |
| `t.instant` | `java.time.Instant` (microsecond precision) |
| `t.duration` | `kotlin.time.Duration`; a duration in years or months refuses to decode |
| `t.maybe(x)` | `X?` |
| arrays, maps | `List<X>`, `Map<String, X>` |
| objects | generated data classes |
| other unions | `com.bijection.client.Value` |

## Change entries

A query returning `selection.changes` answers `List<Change<Fact>>`. Each
`Change` has `key`, `before` (null on an insert), `after` (null on a delete) and
`version`.

## Android

An Android app uses the same `com.bijection:client-kotlin` and the generated
`connect`. Calls go over `HttpURLConnection`; give watches a `LiveFactory`
(see [Watch](#watch)).

```kotlin theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
val client = connect(url, ConnectOptions(live = myLive))
```

To sign in through an identity provider, implement `AuthProvider<T>` and pass
`SignIn(provider)` as `tokenSource`; `login`, `loginFromCache`, `logout` and
`authState` drive it. A provider that shows UI holds its own `Activity`.
`SignIn` answers `kotlin.Result`; the client's own result type is
`com.bijection.client.Result`, so qualify one of them where both are in
scope.


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