Kotlin
Build Jazz apps in Kotlin, for Android and the JVM, with the jazz-kotlin library and typed bindings generated from your schema.ts.Kotlin is for apps: Android apps and JVM desktop or command-line clients. Your app's main backend
runs in TypeScript. You describe your app once, in schema.ts, and a Kotlin app gets typed
bindings generated from it, like every other language. It syncs as an end user through your
backend's Jazz endpoint (createJazz's handler), or runs locally.
The jazz-kotlin library wraps Jazz's native core (jazz-ffi, through JNA). Its calls are
suspend functions, and subscriptions are Flows. It runs on JDK 17 or later, and on Android
(minSdk 24).
Install
jazz-kotlin is on Maven Central, at the same version as every Jazz package. On the JVM, depend on
tools.jazz:jazz-kotlin:
build.gradle.ktsplugins {kotlin("jvm") version "2.2.21"kotlin("plugin.serialization") version "2.2.21" // for the generated bindingsapplication}repositories { mavenCentral() }dependencies {implementation("tools.jazz:jazz-kotlin:2.0.0-alpha.66")}
The jar has libjazz_ffi for Linux (x86-64, arm64), macOS (arm64, x86-64) and Windows (x86-64)
inside, which JNA loads from it. It brings kotlinx-serialization-json,
kotlinx-coroutines-core and JNA with it.
On Android, depend on tools.jazz:jazz-kotlin-android instead:
app/build.gradle.ktsdependencies {implementation("tools.jazz:jazz-kotlin-android:2.0.0-alpha.66")}
Its AAR has libjazz_ffi for arm64-v8a, armeabi-v7a and x86_64, and brings JNA's Android build.
Apply kotlin("plugin.serialization") for the generated bindings, and keep tools.jazz.**,
uniffi.jazz_ffi.** and com.sun.jna.** if you minify.
To build from source: in a Jazz checkout,
cargo build -p jazz-ffi --release, then either build the jar with Gradle in packages/jazz-kotlin
(it bundles your platform's library) or set -Djna.library.path to target/release.
Generate the bindings
Your app's tables and permissions live in schema.ts, written with the same s.defineSchema DSL
as a TypeScript app's (see Defining Tables and
Permissions). Put it beside your build.gradle.kts and run generate
there:
npx jazz-tools generate # writes jazz.app.json, jazz.permissions.json and src/main/kotlin/JazzApp.ktnpx jazz-tools generate --check # in CI: fails if any of them is stale
generate picks Kotlin when the build script beside schema.ts (build.gradle.kts or Groovy
build.gradle) depends on jazz-kotlin or jazz-kotlin-android, by coordinate or as the release's
jar or AAR (files("libs/jazz-kotlin-….jar")). Otherwise pass --lang kotlin. The project needs
no package.json.
If your Kotlin app is a client of an app whose schema lives elsewhere (say, beside your web app),
its schema.ts can re-export that one, as StagePlan's Kotlin CLI does:
schema.tsexport { schema, permissions } from "../web/schema";
Commit schema.ts and everything generate writes; change schema.ts, never the JSON or
JazzApp.kt, and run generate again. JazzApp.kt is in the package jazzapp, and per table it
gives you:
- a
@Serializablerow data class (Task), with the authored column names; - a new-row data class (
NewTask), whose optional columns default tonull; - a patch builder (
TaskPatch), used asjazz.update(Tasks, id) { status(TaskStatus.Done) }; - a table object (
Tasks) with typed columns, for queries:Tasks.where(Tasks.showId eq id).orderBy(Tasks.rank.asc()); - an
enum classper enum column (TaskStatus).
Import the generated declarations by name (import jazzapp.Tasks, import jazzapp.NewTask), or
write them qualified (jazzapp.Result), rather than import jazzapp.*: a star import outranks
Kotlin's default imports, so a table such as results would hide kotlin.Result in your code.
Names are the ones schema.ts uses: a showId column is showId, and a due_at column stays
due_at (only names that aren't Kotlin identifiers are camel-cased). Values are plain Kotlin types:
uuid is a String, int an Int, bigint a Long, float a Double, timestamp a Long
(milliseconds since the epoch), bytea a ByteArray, json a JsonElement, an array a
List<T>, an enum its generated enum class, and an optional column is nullable. The file names
these fully qualified (kotlin.String), so a table may be called Result or Unit.
Open the app
The app syncs through your backend's Jazz endpoint (createJazz's handler, e.g.
https://app.example/jazz), never with the sync server's secrets. It signs in with a local-first
device account:
DocsSnippets.kt// An end user's app: it syncs through your backend's Jazz endpoint, signed in// with a local-first device account (keep the key in the platform keychain).val jazz = jazzapp.open(JazzConfig(appId = appId,serverUrl = endpoint, // e.g. "https://app.example/jazz"storage = Storage.Persistent,dataDir = System.getProperty("java.io.tmpdir") + "/stage-plan-" + appId,auth = JazzAuth.DeviceAccount(deviceKey), // JazzAuth.generateDeviceKey() once),)
or as a user your backend signs in, with their bearer token:
DocsSnippets.kt// A user your backend signs in: Jazz asks for their token when connecting,// before it expires, and after the server refuses one.val jazz = jazzapp.open(JazzConfig(appId = appId,serverUrl = endpoint,auth = JazzAuth.Bearer { reason -> fetchToken(reason.fresh) },),)val me: String? = (jazz.session.value as? SessionState.SignedIn)?.user?.account
jazz.session and jazz.syncStatus are StateFlows of who is signed in and how the app syncs;
jazz.link(bearer) joins a device account to your sign-in:
DocsSnippets.kt// The session and sync status as StateFlows: collect them in your UI.when (val session = jazz.session.value) {is SessionState.SignedIn -> seen += "signed in as ${session.user.subject}"is SessionState.Expired -> seen += "session expired (${session.reason}): sign in again"SessionState.SignedOut, null -> seen += "signed out"}val sync: SyncStatus = jazz.syncStatus.valueif (sync.link is Link.Offline) seen += "offline"if (!sync.synced) seen += "${sync.pendingUploads} changes to upload"jazz.refreshSession() // ask for a fresh token nowjazz.signOut() // also closes the app
Jazz is safe to use from any coroutine: its calls are main-safe suspend functions, and the
native core syncs on a thread of its own. Call jazz.close() (it's AutoCloseable) when you're
done; closing ends open watches and subscriptions with JazzException.Closed.
Writes are local-first: a write the server's permissions refuse doesn't fail the call, it rolls
back once the server answers. Write at WriteTier.Global (or call waitForSync) to see the
refusal as a JazzException.Permission.
The Reading and Writing pages have a Kotlin
tab for each example. examples/stage-plan/apps/kotlin-cli in the repository is a complete
end-user app: it signs in, creates a show, lists its tasks by rank, adds tasks and moves them
between stages.
Edit text
A "merge": "text" column (like StagePlan's tasks.notes) is written as an edit of what you
read, so concurrent edits merge. jazz.edit(table, id) { … } also splices text and bytes and sets
values inside JSON columns.
Text positions are UTF-16 code units, Kotlin's String indices, as Android's EditText
selections and Spannable ranges count them: splice(column, from, to, …) and column.range(from, to) take them as they are. Pass SpliceUnits.Utf8 for UTF-8 byte offsets, and SpliceUnits.Bytes
for a bytea column.
DocsSnippets.kt// tasks.notes is "merge": "text": write it as an edit of what you read, and// concurrent edits by others merge instead of one overwriting the other.val before: String = task.notes ?: ""jazz.editText(Tasks, task.id, Tasks.notes, editedFrom = before, text = "$before\nBring gaffer tape.")
Hops, unions and history
Follow a relation from a query's rows (hopTo); gather(relation, maxDepth) follows a self-relation recursively:
DocsSnippets.kt// The crew members assigned to the show's unfinished tasks: follow the tasks'// `assignee` relation; what comes after the hop filters the crew.val busy: List<Crew> = jazz.all(Tasks.where(Tasks.showId eq showId, Tasks.status ne TaskStatus.Done).hopTo(Tasks.assignee).orderBy(CrewTable.name.asc()),)
Combine queries of one table:
DocsSnippets.kt// Blocked tasks and unassigned tasks, as one list.val attention = jazz.all(Tasks.where(Tasks.showId eq showId, Tasks.status eq TaskStatus.Blocked).union(Tasks.where(Tasks.showId eq showId, Tasks.assigneeId.isNull())).orderBy(Tasks.rank.asc()),)
Read the versions the server accepted (History), at ReadTier.Remote:
DocsSnippets.kt// Every version of a task the server accepted, newest first.val versions: List<HistoryRow<Task>> = jazz.all(Tasks.where(Tasks.id eq taskId).orderBy(JazzColumns.acceptedAt.desc()).history(),tier = ReadTier.Remote,)
Include deleted rows:
DocsSnippets.kt// Deleted rows too, e.g. for an undo list.val withDeleted = jazz.all(Tasks.where(Tasks.showId eq showId).includeDeleted())
Large values
Stream a large text or bytea value in, and read back only the part you need:
DocsSnippets.kt// Stream a large value in, chunk by chunk, without holding it in memory:// nothing is written if the stream fails or the call is cancelled.jazz.updateStreaming(Tasks, taskId, Tasks.notes, notes.chunks())
DocsSnippets.kt// Read only the part of a large value you show: here, the first 80 characters.val preview: String? = jazz.one(Tasks.where(Tasks.id eq taskId).select(Tasks.title, Tasks.notes.range(0, 80)),)?.get(Tasks.notes)
Computed fields and transforms
If schema.ts declares computed fields or transforms, the bindings declare an
interface JazzComputed (e.g. tasksPriority(score: Int): TaskPriority,
isoDateView(stored: Long): String and isoDateStored(view: String): Long), and
jazzapp.open(config, computed) takes your implementation, so a missing one doesn't compile. Rows
carry each computed field and each transformed column's view value; inserts and patches take the
view value. Queries compare a transformed column as stored.
Not supported yet
In Kotlin, Jazz doesn't support these yet:
- reading part of a large value inside an include (root queries only);
- guest (anonymous) users;
- nested rows, catalogue enums and transaction-id columns in bindings;
- Kotlin Multiplatform targets other than the JVM and Android;
- non-finite doubles (
NaN, infinities): writing or comparing one throws, as JSON has none; limitandoffsetwithwatch: they apply to the server's result beforewatchre-sorts it locally, so a page can be off after changes. Use them withall.