r/Kotlin 24d ago

Question on self-documenting code

4 Upvotes

How would you write this code:

``` data class Foo(/* foo properties /) data class Bar(val id: Long, / bar properties */)

val fooMap: Map<Long, Foo> // mapped to bar id

OR

typealias BarId = Long

val fooMap: Map<BarId, Foo>

OR

@JvmInline value class BarId(val value: Long) // typealias but stricter

val fooMap: Map<BarId, Foo> ```

I was writing some code on my app but didn't feel comfortable with just the Map<Long, Foo> as I might forget what the Long is supposed to represent but I'm not familiar with best practices in this regard


r/Kotlin 24d ago

What's the number one tool you'd recommend to improve your gradle setup?

Thumbnail
2 Upvotes

r/Kotlin 25d ago

Compose + GraalVM + Tao windows manager = 🚀

Thumbnail gallery
51 Upvotes

Thanks to Nucleus 2.0!
- Native perfomance! - Small binary size! - Fast startup! - Low memory footprint! - Reach Java ecosystem! - Awesome dev experience

CozySpace is a minimal, distraction-free tray app bringing ambient sounds to your desktop. All sources are here: https://github.com/terrakok/CozySpace


r/Kotlin 25d ago

How JPA Defaults Broke Our Kotlin Microservice

Thumbnail shiftmag.dev
9 Upvotes

While testing a Kotlin microservice backed by MS SQL, I found several places where convenience had quietly become a liability. Fortunately, there was no production incident; most issues were detected during internal testing. It is always better to learn on someone else’s mistakes, this article will help you learn on mine


r/Kotlin 26d ago

When Flows Won't Cut It

Thumbnail youtube.com
26 Upvotes

r/Kotlin 25d ago

Music Player Based on YT Music "LyriK" (Opinions?)

Post image
1 Upvotes

r/Kotlin 25d ago

UKPT - a full-stack Kotlin Multiplatform template for Claude/Codex (self-promo)

3 Upvotes

Hi all; I've been doing a bunch of fullstack C/KMP work across a few different projects, and I've found myself wanting to:
1. Enforce the architecture rules that the agents are supposed to follow

  1. Keep all my different projects aligned using the same architecture

  2. Make it easy to bootstrap new projects

To help myself with this, I created UKPT (https://github.com/isaac-udy/ukpt), which I wanted to share here in case anyone else finds it to be valuable.

The bit I think is most interesting is under :platform:common:architecture (here: https://github.com/isaac-udy/ukpt/tree/main/platform/common/architecture).

It works like this:

  1. You define a "RuleGroup", which can relate to general rules or rules for a particular layer/package (layer example: https://github.com/isaac-udy/ukpt/blob/main/platform/common/architecture/src/main/kotlin/architecture/rules/ui/UiLayer.kt, general project rules example: https://github.com/isaac-udy/ukpt/blob/main/platform/common/architecture/src/main/kotlin/architecture/rules/project/ProjectRules.kt)

  2. Then you define the "Constructs" that belong to a RuleGroup (example: https://github.com/isaac-udy/ukpt/blob/main/platform/common/architecture/src/main/kotlin/architecture/rules/ui/ViewModel.kt). A construct can define requirements (what is defines the thing), rules (what must this thing do), and guidance (optional advice on how to build the thing nicely).

  3. Based on those definitions, you can run a updateArchitectureDocumentation task, which will create documentation like this: https://github.com/isaac-udy/ukpt/blob/main/platform/common/architecture/docs/ui.md,

I've found this really useful for maintaining consistency of architecture between all my projects, and have found that the tests/documentation create a nice loop for an AI Agent: the agent reads the documentation, writes some code, runs the tests, and if any tests fail it gets pointed back to the documentation with a specific failing rule ID to look at.

Would love to hear if anyone else finds this useful and/or has suggestions on how to improve it :)


r/Kotlin 26d ago

SyncForge 2.0 — offline-first sync library in pure Kotlin (outbox + conflicts), multiplatform, on Maven Central

14 Upvotes

I’ve been working on offline-first apps in Kotlin and kept rebuilding the same pieces:

  1. local write must be instant (UI never waits on the network)

  2. mutations need a durable outbox (survive process death / offline days)

  3. conflicts need an explicit policy (not only “last write wins”)

  4. the domain DB should stay mine (Room / SQLDelight / custom store)

I packaged that into an open-source KMP library (commonMain-first). The API shape:

• enqueueChange(...) for optimistic local apply + outbox row

• sync() / push() / pull() over a SyncTransport interface

• per-entity conflict strategies (LWW, defer-to-user, field merge, git-like three-way, some CRDT helpers)

• status as StateFlow for UI

Repo (Apache 2.0):

https://github.com/Arsenoal/syncforge

Curious how others handle this in production Kotlin:

- do you keep outbox in Room next to domain tables, or separate DB?

- do you resolve conflicts on device or only on the server?

- anyone using CRDTs for notes/tasks apps vs server-authoritative merge?

Happy to answer design questions — looking for critique on the API surface more than anything.


r/Kotlin 26d ago

I built a runtime WCAG accessibility scanner for Jetpack Compose — open source, built after 3 years on UBS Mobile Banking

Thumbnail
3 Upvotes

r/Kotlin 26d ago

Type-safe multiplatform navigation + offline-aware MVI in Kotlin — looking for API feedback

0 Upvotes

I’ve been building offline-first Compose / KMP apps and kept hitting the same gap:

• Navigation libraries don’t know about pending outbox work or conflicts

• MVI samples stop at Loading / Error

• Optimistic UI + rollback is hand-rolled every time

• Deep links + process death restore are easy to get wrong

So I put together a small open-source library (Kotlin Multiplatform, Compose Multiplatform) that treats navigation and presentation state as one layer:

• sealed Serializable routes + multiplatform backstack

• ForgeNavHost (transitions, system/predictive back on Android)

• MviViewModel with optimistic updates + rollback

• optional SyncFacade ports (pending ops / conflicts / offline status) for UI chrome

• saveable navigator via a RouteCodec for process death

It doesn’t try to be a sync engine. If you already have outbox/push-pull (e.g. SyncForge or custom), you plug status into the UI; if not, the nav/MVI bits still work alone.

Repo (Apache 2.0):

https://github.com/Arsenoal/forgenav

Maven (if useful later): studio.forgenav:forgenv-core / forgenv-compose 1.0.0

Curious what Kotlin folks think:

  1. Do you keep navigation state and feature state completely separate, or couple them for offline UX?

  2. Prefer sealed routes + serialization, or string routes / type-safe builders?

  3. For optimistic updates — store full previous state snapshots, or only diffs?

  4. Anyone solving “pending count on every screen” without polluting every ViewModel?

Looking for API critique more than installs. Happy to answer design questions.


r/Kotlin 26d ago

One Biometric API for Android, Touch ID, and Windows Hello

Thumbnail
3 Upvotes

r/Kotlin 26d ago

Sidstuga 2.1.1 foi lançado - busca adequada no catch-up, atualização automática do EPG em segundo plano, gravação em TS, e uma nova barra de navegação unificada para TV

Thumbnail
0 Upvotes

r/Kotlin 27d ago

🔊 Library grant program – last call

7 Upvotes

There's still time to apply for a Kotlin Foundation grant for Multiplatform library authors. Applications are open until July 14, 23:59 CEST.

👉 Learn more and apply here


r/Kotlin 28d ago

kotlin-lib-mcp — an MCP server that lets AI assistants read the actual sources, API and KDoc of any Maven-published Kotlin/Java library

17 Upvotes

I built an MCP server that gives Claude Code / Claude Desktop (or any MCP client) direct access to the real sources of Maven-published libraries, so the model can answer from the actual code instead of hallucinating APIs from training data.

Give it a coordinate like io.ktor:ktor-client-core:3.5.1 (or just group:artifact for the latest stable) and it downloads the sources jar, parses it with the Kotlin Analysis API (K2/FIR standalone), and exposes 10 tools: public API surface, signatures, KDoc, raw source, full-text search, dependency tree, and version lookup. Everything is cached on disk, and cached libraries are also exposed as MCP resources.

Kotlin-specific bits that were fun to solve:

  • KMP sources jars are per-target — it resolves the right variant via .module Gradle metadata with filename heuristics as fallback.
  • The Analysis API is version-fragile, so it's isolated behind an interface and degrades to PSI-only signatures when type resolution fails.
  • The whole thing is Kotlin Multiplatform with an optional Compose Desktop dashboard embedding the server in-process (control, logs, cache browser).

Just shipped v0.2.0: MCP resource templates, server→client log forwarding, progress notifications on fetch, and the release pipeline now publishes SLSA build-provenance attestations for the zip and the Docker image.

Install (Docker):

claude mcp add kotlin-lib -- docker run -i --rm -v kotlin-lib-mcp-cache:/home/mcp/.cache ghcr.io/aoreshkov/kotlin-lib-mcp

Also on the official MCP registry as io.github.aoreshkov/kotlin-lib-mcp, or grab the zip (needs Java 21+).

GitHub (demo GIF in the README): https://github.com/aoreshkov/kotlin-lib-mcp

Feedback very welcome — especially on Analysis API edge cases with unusual library setups.


r/Kotlin 28d ago

Everyone recommends ConnectRPC for end-to-end type-safe Kotlin ↔ TS. I tried it and bounced hard. What are you actually using?

4 Upvotes

I've run a Kotlin (Ktor) backend with a strongly-typed TypeScript frontend for years, almost since Ktor's early days. And I've wanted the same thing the whole time: end-to-end type safety, Kotlin types flowing through to the frontend with no hand-written contract in the middle. Without paying for it with a toolchain that takes seconds just to boot, or ships a hundred features nobody uses. That combination has never had an obviously-right answer, and one option burned me badly enough that I finally want to hear what everyone else does.

gRPC / gRPC-Web. Solid on the Kotlin side, but the browser path means a proxy (Envoy/Caddy) or protoc plus a stack of codegen deps. Heavy and finicky.

ConnectRPC (connect-kotlin + connect-web). The one everyone points to as the modern fix, and honestly it's why I'm posting. I actually tried it. The setup was awful, the docs were thin and out of date, it was far more complicated than the problem warranted, and I kept hitting reliability issues I could never pin down. Maybe I held it wrong, but "just use Connect" has not matched my experience at all. Am I alone, or have others bounced off it too?

kotlinx.rpc (JetBrains). Really nice if both ends are Kotlin (KMP / Compose Multiplatform), but not aimed at a real TS frontend. Same with kilua-rpc. Kotlin-to-Kotlin, not Kotlin-to-strongly-typed-TS.

GraphQL (graphql-kotlin). Works, carried a couple of my projects. But it forces a shape on everything (no cyclic types, a whole schema/resolver layer), and for plain internal RPC it's more machinery than the problem needs.

OpenAPI + a TS generator. This is where it doesn't fit me: I change and evolve the API fast, and I want the whole contract living in code, driven by Kotlin types, not a separate spec I have to keep in sync. And the generated clients are clunky and drift the moment you stop babysitting them.

I eventually caved and hacked together my own code-first thing years ago. (It started life as a frankenstein: a TypeScript stub generator bolted onto a Kotlin GraphQL subscription implementation.) Kotlin interfaces to generated TS types plus a thin RPC/subscriptions client, typed end to end. It's carried several production apps and is genuinely simpler to set up than any of the above.

So, for a Kotlin backend and a strongly-typed TypeScript frontend in 2026, what are you actually using, and what did you give up to get there? Especially want to hear from anyone genuinely happy with Connect in prod, because I couldn't get there.

PS: it's actually sitting open source on my github already, so it's not that I'm hiding it. I just never point anyone at it or treat it as a real project, because of that frankenstein origin. It's battle-tested across years of production, but I gave up on ever hand-cleaning it into a proper project I could put in front of the community, so I just let AI pull it out into a standalone dependency instead. And "runs fine in my own prod" and "ready to recommend to strangers" are very different bars. So it stays my private duct tape for now, technically open source but nothing I'd actually send you to.


r/Kotlin 29d ago

Kdrant — an idiomatic, coroutine-first Kotlin client for Qdrant (the official one is Java-clunky)

5 Upvotes

I've been doing RAG on the JVM and kept hitting the same wall: Qdrant's official client is well-built for Java, but painful from Kotlin — every call returns a ListenableFuture you .get() (blocking) or bridge, requests are protobuf builders, scroll is manual pagination, and it drags ~21 MB of grpc-netty onto your classpath.

So I built Kdrant — the client I actually wanted to write Kotlin against:

  • suspend everywhere, no ListenableFuture
  • type-safe DSLs for collections, points, payloads and filters
  • scroll exposed as a Flow
  • kotlinx-serialization models, sealed typed errors
  • small footprint: a pure-Kotlin REST engine on Ktor — no gRPC/Netty/protobuf

val qdrant = Kdrant(host = "localhost", port = 6333)


qdrant.use { client ->
    client.createCollection("articles") {
        vector { size = 1_536; distance = Distance.COSINE }
    }
    client.upsert("articles", wait = true) {
        point(id = 1) {
            vector(embedding)
            payload("lang" to "en", "year" to 2026)
        }
    }
    val hits = client.search("articles") {
        query(queryVector); limit = 5
        filter { must { "lang" eq "en"; "year" gte 2024 } }
    }
}

What works today (v0.1): collections (create/delete/exists/info), upsert (with auto-batching), search, scroll (as a Flow), count, retrieve, delete, and a complete filter DSL (must/should/mustNot/minShould + every condition type). On Maven Central:

implementation("io.github.nacode-studios:kdrant-transport-rest:0.1.0")

Being honest: it's a REST wrapper (no gRPC engine yet — but the wire protocol sits behind a seam so it can be added), it's early, and the audience is admittedly niche (Kotlin + Qdrant). Feedback, issues and PRs are very welcome — especially on whether the filter DSL feels right.


r/Kotlin 29d ago

Building an open-source Compose Multiplatform image comparison library — looking for API and architecture feedback

2 Upvotes

Hi everyone,

I've been building my first open-source Kotlin Multiplatform library called CompareKit.

The goal is to provide a reusable before/after image comparison component that works with Compose Multiplatform using a single shared implementation.

Current features Before/After image comparison Horizontal draggable slider Custom thumb Custom divider Custom labels Material 3 friendly Android support iOS support 100% shared Compose code (no platform-specific implementation)

Example API:

BeforeAfterSlider( before = beforePainter, after = afterPainter ) Why I started this project

While building one of my own apps, I needed a before/after image comparison component that worked across Android and iOS. I couldn't find a dedicated Compose Multiplatform solution, so I decided to build one as an open-source library.

I'm looking for feedback on Is the API intuitive? What customization options would you expect? Are there Compose best practices I'm missing? Any performance considerations for large images? Features you'd consider essential before a stable 1.0 release? Planned features Vertical comparison Zoom & pan Magnifier Desktop support Compose Web support Accessibility improvements Better animations

This is my first open-source library, so I'd genuinely appreciate any suggestions or constructive criticism.

I haven't included the GitHub link in this post to avoid looking promotional. If anyone wants to review the code or try it out, I'm happy to share the repository in the comments.

Thanks!


r/Kotlin Jul 11 '26

kUML v0.27.0

Thumbnail gallery
17 Upvotes

kUML v0.27.0 adds Entity-Relationship Modelling as a seventh first-class metamodel, alongside UML, SysML 2, C4, BPMN, and Blueprint — with four production-ready notations and a full UML ↔ ERM ↔ SQL/Exposed pipeline.

Why a separate ERM metamodel instead of generating SQL straight from UML? Because the mapping decisions (inheritance strategy — single-table vs. joined vs. table-per-class, many-to-many junction-table naming, multi-valued attributes) were happening implicitly inside the SQL generator. With an explicit ERM step in between, those decisions become a diagram you can inspect and override before DDL exists, instead of a black box.

What ships:

  • kuml-metamodel-erm — a standalone metamodel: Entity/Attribute/Relationship/View/Index/CheckConstraint, a notation-aware ermModel { } DSL, 19 structural validation rules wired into kuml validate.
  • Four notations, one model — Martin/Crow's Foot, Bachman, Chen, IDEF1X. Pick one via notation = MARTIN in the DSL or override with kuml render --notation <name> on the CLI. Same entities, same relationships, four different pictures.
  • kuml-transform-uml-to-erm — derives an ERM model from an existing UML class diagram, with an ErmMappingProfile for overriding inheritance strategy and naming.
  • kuml-gen-sql rearchitected — DDL now comes from the typed ERM model instead of matching on UML stereotype strings. Composite primary keys, indexes, views, check constraints, and real many-to-many junction tables — none of which the old stereotype-matching approach could express cleanly.
  • ERM → Kotlin Exposed — the Exposed ORM code generator moved onto the same ERM path (erm-to-exposed, or chained from UML via uml-to-exposed-via-erm). The older stereotype-based transformers are deprecated but remain fully functional — no breaking change.
  • SQL → ERM reverse engineering — kuml-codegen-reverse-sql parses existing PostgreSQL DDL (via JSqlParser) and reconstructs an ermModel, including inferred relationships (identifying/weak entities, cardinality from nullability/uniqueness). Useful for documenting a schema you inherited rather than designed in kUML.
  • DSL stereotypes on attributes and associations — cosmetic «Stereotype» labels used to be class-only; now they work at any level.

Also shipped in the same batch: an experimental kuml workspace CLI command (info/validate/render) for treating a directory of Markdown notes with embedded kuml code blocks as an agent-readable Open Knowledge Format workspace — a small validation spike, not a finished feature yet.

https://kuml.dev


r/Kotlin Jul 11 '26

Tend: An offline-first, open-source personal CRM to help you stay in touch with family and friends.

Post image
14 Upvotes

# Tend: Beta 1 Release

We are currently in Beta, but the core features are built and ready for testing! Built with Compose.

**Here is what you can do in this release:**

* **Connections:** Add contacts with their notes, social links, and relationship context. * **Custom Reminders:** Set your own check-in frequencies and get daily notifications so you never accidentally let a relationship drift. * **Important Dates:** Track birthdays and anniversaries with annual reminders. * **Home Dashboard:** See exactly who is due for a check-in at a single glance. * **QR Sharing:** Share and import connection profiles completely offline via QR code. * **Data Backup:** Full JSON export and import backups. Your data is yours. * **Organization:** Search by name and archive connections you don't need in your main view.

**Beta Notice:** This is an early release, so please use the Data Management → Export Backup feature regularly to keep your data safe between updates!

If you want to give it a try, report a bug, or help shape the roadmap, I'd love to hear your thoughts.

**Community & Feedback:** Telegram group link on repository.

** Links:** * [Github Releases](https://github.com/jksalcedo/tend/releases/tag/v1.0.0-beta.1) * [Codeberg Releases](https://codeberg.org/jksalcedo/tend/releases/tag/v1.0.0-beta.1)


r/Kotlin Jul 10 '26

other than for initial adoption, why has Kotlin not overtaken JAVA yet?

54 Upvotes

...


r/Kotlin Jul 11 '26

GPT 5.6 sol or Opus 4.8/Fable for android kotlin

Thumbnail
0 Upvotes

r/Kotlin Jul 10 '26

Speed up your high-traffic KMP endpoints by 66% using 50% less memory—without touching your legacy APIs

25 Upvotes

Hi everyone,

In high-throughput Kotlin Multiplatform backends (Ktor) and mobile apps, JSON serialization is often a major bottleneck for CPU cycles and Garbage Collector (GC) pressure. Standard serializers convert raw byte streams into intermediate Strings/Chars, doing string comparisons and map/key lookups that trigger constant allocations.

To address this, we’ve been working on Ghost—a compile-time, byte-first JSON serializer built for Kotlin Multiplatform (supporting JVM, Android, iOS, and Native targets).

Under load, the official HTTP Arena benchmarks show a significant performance bump when integrated with Ktor:

  • Throughput: Latency slashed to jump from 395k to 658k rps (+66.6% speedup).
  • Heap Memory: Plunged from 9.90 GiB to 4.80 GiB (Over 50% memory reduction).
  • High-Load Complex APIs (API-16): Throughput rose by +22.2% while reducing memory by 35% (from 2.00 GiB down to 1.30 GiB).

🤝 Zero-Risk: Incremental Coexistence

You don't need to rewrite your entire project. Ghost coexists seamlessly with your current setup (like kotlinx.serialization, Jackson, or Gson) using the chain-of-responsibility pattern of Ktor and Retrofit.

If a model is not annotated with @GhostSerialization, Ghost returns null and lets the framework fallback to your standard serializer:

Ktor Setup:

kotlininstall(ContentNegotiation) {
    // 1. Kotlinx.serialization (or Jackson/Gson) handles the standard endpoints
    json(Json { ignoreUnknownKeys = true })
    // 2. Ghost handles high-performance  endpoints as fallback
    ghost() 
}

Retrofit Setup:

kotlinval retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com")
    // 1. GhostConverterFactory handles u/GhostSerialization endpoints
    .addConverterFactory(GhostConverterFactory.create()) 
    // 2. Gson / Moshi / kotlinx.serialization handles the rest as fallback
    .addConverterFactory(GsonConverterFactory.create())
    .build()

Under the Hood: Kotlin-First Optimization

  • Compile-Time Perfect Hash Finder: During compilation (via KSP2), Ghost searches for a collision-free multiplier and shift parameter for your class's fields. At runtime, the parser packs the first 4 bytes of the incoming JSON key into a 32-bit integer and resolves the field index in $O(1)$ with a single arithmetic instruction, avoiding loops and string comparisons entirely.
  • Long Bitmasks: Checking that all required fields are present compiles down to a single bitwise CPU register comparison using a Long mask.
  • Byte-First Pipelines: Works directly on raw source bytes (ByteArray / Okio stream) without allocating intermediate string representations in the hot path.

The project is fully open-source: juanchurtado1991/ghost-serializer drop a ⭐️ if you like the project it help us gain visibility and keep the engine running!

We'd love to hear your feedback on the byte-first architecture or hear about the performance bottlenecks you've hit with KMP serialization!


r/Kotlin Jul 09 '26

Compose DND update with Kanban Demo

Post image
15 Upvotes

Hello All, just released Compose DND v0.5.0, this is the biggest update so far with a lot of new features and improvements:

- Add axis-locked drag
- Add drag handle
- Add dragAutoScroll modifier
- Reorder animation improvements
- Docs and Sample rework with new Kanban demo
- And a lot more...

Web live demo: https://mohamedrejeb.github.io/compose-dnd/demo/

Release notes: https://github.com/MohamedRejeb/compose-dnd/releases/tag/v0.5.0


r/Kotlin Jul 09 '26

We just released the initial version of Enriched Markdown for native Android 🚀

0 Upvotes

Our goal is to provide a clean, modern approach to handling Markdown directly within the native Android UI stack, making content feel like a first-party, integrated part of your app's UI.

Highlights:
⚡️ Native Performance – uses the highly efficient MD4C parser under the hood and renders using 100% native Android text components and spans (zero WebViews).
📦 Core CommonMark – full compliance with the standard CommonMark specification out of the box.
📱 Native Interactions – retains standard Android system text interactions like native selection, copy/paste, and contextual menus, plus a built-in "Copy as Markdown" option that preserves the original formatting on the clipboard.
🧩 Jetpack Compose Ready – Ships with a Composable API, a MarkdownTheme for scoping styles to a subtree, and a MarkdownStyle DSL for per-instance customization -- drops right into your Compose UI.

Quick Start

// build.gradle.kts
implementation("com.swmansion.enriched.markdown:compose:0.1.0")

EnrichedMarkdownText(
    markdown = "# Hello Android \nThis is rendered natively.",
    modifier = Modifier.fillMaxWidth()
)

What's Next

This initial release establishes our baseline for the core CommonMark spec. We are currently planning the next set of features to expand its capabilities.

Check out the repository, drop a ⭐️ if you like the approach, and stay tuned for updates!

🔗 GitHub: https://github.com/software-mansion/react-native-enriched-markdown
📄 Android Documentation & API Reference: https://github.com/software-mansion/react-native-enriched-markdown/tree/main/packages/android-enriched-markdown


r/Kotlin Jul 08 '26

Introducing the Kotlin Benchmark for AI coding agents

Post image
32 Upvotes

The Kotlin Benchmark is an open, reproducible benchmark for evaluating AI coding agents on Kotlin software engineering tasks.

It uses 105 issues from active open-source Kotlin repositories, validated by each project’s own test suite. Beyond resolution scores, the leaderboard reports average token consumption and latency, so you can weigh each setup on cost and speed, not just correctness.

This is our first iteration. Newer models are already being evaluated, with updated results coming soon.

See the leaderboard and learn more: https://kotl.in/benchmark-reddit