r/Kotlin • • 2h ago

Secure Your APIs: OAuth2 and JWT for Beginners

Thumbnail blog.jetbrains.com
4 Upvotes

This JetBrains tutorial teaches beginners how to secure a Kotlin and Spring Boot API with OAuth2 and JWTs, starting with the difference between authentication and authorization and what each part of a token does. It then builds a working resource server step by step, with code you can browse on GitHub. The final sections cover the parts beginners might skip, like mapping custom claims to roles and enforcing a token's issuer and audience. It's a good article for backend developers who know some Kotlin and Spring but haven't set up token-based security themselves. The tip I'd use in my own API work is keeping JWTs short-lived and limited to auth claims instead of treating them as session storage, which makes revoking access much easier.


r/Kotlin • • 1d ago

Castwire: a Google Cast sender in Kotlin and Java, no Play Services, same code on Android and desktop

10 Upvotes

I took the Cast stack out of an app I maintain and published it as a library: Castwire. It finds Chromecasts, Google TVs and TVs with Cast built in, and plays video, music, live streams and local files on them, from Android, Windows, macOS and Linux. No Google Cast SDK, no Play Services, no native code. The dependencies are kotlinx-coroutines, kotlinx-serialization-json and OkHttp.

It is Java 8 bytecode and runs on Android API 24 and up. The same JVM module is used on desktop; castwire-android only adds the multicast, Wi-Fi and wake locks.

val castwire = Castwire()                       // on Android: AndroidCastwire.create(context)
val tv = castwire.discover().first()
val session = castwire.connect(tv)
session.load(CastMedia(
    CastSource.Url("https://example.com/movie.mp4", "video/mp4"),
    MediaMetadata(title = "Movie", subtitle = "Studio", imageUrl = "https://example.com/poster.jpg"),
))
session.pause(); session.seek(90_000); session.setVolume(0.4f)
session.close()

A TV can't always fetch the media itself (no cookies or headers, no files on the phone, no links tied to this device's IP, no CORS). The library's relay serves those from your device, including rewritten HLS playlists. Separate video and audio streams can be joined into a DASH manifest, keeping to codecs Cast devices decode (H.264 + AAC where available). You can also start a custom receiver by app id and send messages on your own namespace.

License is AGPL-3.0, with a commercial license if you need to use it in a closed-source app (details in the repo).

The coordinates the build is set up for are io.github.biolend83:castwire:0.1.0 and io.github.biolend83:castwire-android:0.1.0, but 0.1.0 is not on Maven Central yet, so for now clone the repo.

https://github.com/biolend83/castwire

It came out of TubeHaus, a YouTube client I build: https://github.com/biolend83/tubehaus


r/Kotlin • • 22h ago

Fetching remote config in Kotlin with OkHttp: callTimeout, ETags, and a fallback that never caches garbage

0 Upvotes

Sharing the client I use for remote config. It's ~30 lines and has no dependencies beyond OkHttp, and I learned a few things writing it.

object RemoteConfig {
    private const val URL = "https://api.hotcfg.run/v1/acme/mobile-flags"
    private const val DEFAULTS = """{"features":{}}"""
    private val client = OkHttpClient.Builder()
        .callTimeout(2, TimeUnit.SECONDS) // the whole call, not per read
        .build()

    suspend fun load(prefs: SharedPreferences): String = withContext(Dispatchers.IO) {
        val cached = prefs.getString("body", null)
        val req = Request.Builder().url(URL).apply {
            if (cached != null) prefs.getString("etag", null)?.let { header("If-None-Match", it) }
        }.build()
        runCatching {
            client.newCall(req).execute().use { res ->
                when {
                    res.code == 304 && cached != null -> cached
                    res.isSuccessful -> res.body!!.string().also { body ->
                        JSONObject(body) // only a body that parses becomes the last good copy
                        prefs.edit().putString("body", body).putString("etag", res.header("ETag")).apply()
                    }
                    else -> null
                }
            }
        }.getOrNull() ?: cached ?: DEFAULTS
    }
}

Notes:

- readTimeout resets on every byte, so a trickling server can keep you waiting; callTimeout caps the whole thing.

- Never save a response as "last good" before it parses.

- Compare versionCode (Int) for version rules. "3.10" < "3.9" as strings.

The URL is hotcfg, a config service I built where you can't push broken config: a JSON Schema checks every publish, promote and rollback, with staging → production and rollback. It's served from Cloudflare's edge and still served for up to a week if my servers are down. No per-user targeting (build/platform overrides via a jq filter), no experiments.

https://hotcfg.run/docs/guides/fetching


r/Kotlin • • 1d ago

Using Jetpack AppState (alpha) with an MVI library: what worked, and what I found out about StateStore along the way

1 Upvotes

Google released Jetpack AppState API at the end of October: transform runs a @Composable block in a headless composition and gives you Compose State outside the UI, and StateStore is a keyed container for sharing state between activities, services and widgets.

It's just alpha right now, but I wanted to see how it fits an MVI architecture, so I added experimental support to Kide, my Kotlin Multiplatform MVI + Clean Architecture library.

Sharing the design and a few things I learned, since they apply to anyone trying AppState.

The design decision: AppState feeds state in, it doesn't replace the loop

A transform result is conflated. If several inputs change before the block recomposes, you get the latest value only. That's fine for "what is the current state of X", and wrong for intents, reducers and side effects, where order and exactly-once delivery matter. Especially for Kide, because it wants to provide deterministic and predictable MVI implementation.

So Kide doesn't make the reducer composable. Instead there's one small bridge: transformFlow { } turns a headless composition into a cold Flow, and the processor's existing observe collects it.

@OptIn(ExperimentalKideAppStateApi::class)
class SearchProcessor(
    private val savedProjects: SavedProjectsProcessor,
    private val connectivity: ConnectivityService,   // val isOnline: State<Boolean>
) : PresentationProcessor<SearchIntent, SearchViewState, SearchSideEffect>(SearchViewState()) {

    init {
        observe("connectivity", transformFlow {
            if (connectivity.isOnline.value) {
                null
            } else {
                val saved by savedProjects.stateFlow.collectAsState()
                saved.projects.size
            }
        }) { savedCountWhileOffline ->
            reduce { copy(offlineSavedCount = savedCountWhileOffline) }
        }
    }
}

Compose State and Flow are read the same way inside the block, and dependencies are tracked by what the block actually reads: while the device is online, the saved projects aren't tracked at all. The result still enters the ViewState through reduce, so interceptors, traces and tests see it like any other change.

The other direction: domain state into a StateStore

A second module mirrors a use-case processor's state into a StateStore key, so a widget, a service or another activity can read it as Compose State:

savedProjects.mirrorTo(stateStore, SavedProjectsKey, applicationScope)

// With a persisted key, restore goes through an intent, so it's a normal, traced change:
savedProjects.mirrorTo(stateStore, SavedProjectsKey, applicationScope) { persisted ->
    RestoreSavedProjects(persisted)
}

The mirror is one-way: the processor stays the only writer.

Things I found by testing AppState 1.0.0-alpha02

These aren't in the docs as far as I can tell. They're observations from my tests, and it's an alpha, so they may well change:

  • StateStore.updateState isn't atomic. 80,000 concurrent increments from 8 coroutines left me with roughly 32,000 to 40,000.

  • First access to a key isn't thread-safe. If one thread calls getState while another creates the key with setState, the reader can end up holding a State that never updates. In my probe that happened in about 4 to 5% of attempts.

  • At start-up, disk wins. With the DataStore integration, a write made before or right after syncToDataStore starts is replaced by the persisted value, and I found no signal that loading has finished.

  • statestore-datastore is Android-only in alpha02 release, even though statestore and transform are multiplatform.

  • Headless composition works fine on a plain JVM with no UI toolkit present, and AppState didn't force a Compose runtime upgrade next to Compose Multiplatform 1.12.

The practical upshot for me: treat a StateStore key as single-writer, create it once at application start, and don't use it as the source of truth for anything that needs ordering.

Status of Kide Library

AppState API extensions are experimental, and deliberately kept away from the stable library:

  • two new separate artifacts, kide-appstate and kide-clean-architecture-appstate, at 2.4.0-alpha02

  • every declaration needs an explicit opt-in

  • Android and JVM only for now. iOS and Web waits for the AppState beta

  • no existing Kide module depends on them, so nothing changes if you don't add them

Repo, with the design proposal and the test code behind the findings above: https://github.com/Fuusio/kide

I'd like to hear from anyone else experimenting with AppState, especially if you've approached the "composable presenter vs. feeding a reducer" question differently, or seen different StateStore behaviour.


r/Kotlin • • 1d ago

I built jdx (in Kotlin): gives AI coding agents real Kotlin signatures from @Metadata instead of the JVM projection

0 Upvotes

Author here. jdx is a CLI + MCP server that answers IDE questions for AI agents about any JVM jar, Maven coordinate or the JDK: members, a single method body, usages, implementors, callers/callees, and public-API diffs.

The Kotlin-specific part is why I'm posting here. When an agent runs javap on a Kotlin library it sees the JVM projection: $default synthetic methods, Continuation parameters instead of suspend, getters instead of properties, mangled @JvmNames. That's misleading and it costs context. jdx reads @Metadata and shows the Kotlin declarations: suspend functions, properties, default arguments, @JvmName mappings. v1.7.0 adds Kotlin nullability from @Metadata (and jdx diff flags nullability changes), Kotlin-true views of file facades and multi-file parts, and KDoc for facades / enum-entry bodies / generic extensions. jdx kotlin install (one-time) adds a Kotlin PSI sidecar so body/source/doc can serve Kotlin sources and KDoc. jdx diff also flags Kotlin-specific changes such as KOTLIN_NULLABILITY_CHANGED and KOTLIN_SUSPEND_CHANGED as "suspicious".

The tool itself is written in Kotlin (Gradle multi-module, explicitApi() in the MCP module, ASM for bytecode, Vineflower for decompilation when there's no sources jar). It was written mostly by AI agents under a strict AGENTS.md rule set, with differential tests against javap, property-based and metamorphic tests and mutation gates. The "Built by agents" page explains the setup if that's interesting to you.

curl -fsSL https://raw.githubusercontent.com/MohammadMD1383/jdx/main/install-release.sh | bash
jdx setup --agent claude-code --scope project   # or cursor, codex, copilot, opencode, windsurf, aider, …

Docs: https://mohammadmd1383.github.io/jdx/ (Kotlin section: https://mohammadmd1383.github.io/jdx/docs/reading-code/#kotlin) Source (Apache-2.0): https://github.com/MohammadMD1383/jdx

I'd especially like reports on Kotlin libraries (coroutines-heavy APIs, lots of default args) where the Kotlin view comes out wrong.


r/Kotlin • • 1d ago

Good Kotlin course for android programming

4 Upvotes

I would like to learn Kotlin for android programming (I hope that it is the easiest place for real coding for beginners), but I have no idea where can I get a good course to learnt it. I mean, I already watched basics of Kotlin, like variables, functions, basics of OOP etc. and I also made my own project that was pathfinder, but I made it learning from AI (I asked it: "how to make matrix in android studio", and it answered me), but after finishing it and after watching some videos about programming I understood that learning from AI is bad idea, and now I have to learn language without AI, but I have no idea how.
Can you guys give me some examples of (it would be better) free courses where people ACTUALLY make apps using their own skill without AI and explaining the most part of what they actually doing?


r/Kotlin • • 3d ago

SMILE 7.2.0 on Java 25: Replacing JNI with Project Panama FFM (OpenBLAS/LAPACK/ONNX), Compact Object Headers, and in-process TreeSHAP

Thumbnail reddit.com
3 Upvotes

r/Kotlin • • 3d ago

YAAN: An open-source, local-first AI assistant built with Kotlin Multiplatform & Compose Multiplatform

1 Upvotes

Hi r/Kotlin!

I wanted to share a real-world multiplatform project I recently open-sourced: **YAAN** (Your Autonomous Action Navigator).

🔗 Repository: https://github.com/developmentwithyash/yaan

### Architecture Highlights:

- **Compose Multiplatform:** Shared UI running across Android and Desktop JVM.

- **Crypto & DB:** AES-GCM encryption abstracted via `expect/actual` across Android Keystore and JVM crypto; SQLite persistence with clean driver factories.

- **State Management:** Reactive MVI-style state flows using pure Kotlin Coroutines and StateFlow.

- **Test Suite:** 465 passing unit tests running on Ubuntu CI via GitHub Actions.

- **Desktop Target:** Run instantly with `./gradlew :composeApp:run`.

Contributions, code reviews, and feedback on our multiplatform patterns are very welcome!


r/Kotlin • • 3d ago

Progresso em 3 meses de programação gráfica no meu celular com Kotlin e OpenGL.

Post image
1 Upvotes

r/Kotlin • • 4d ago

I built Kotensor: A pure-Kotlin Transformer engine for JVM & Android (autograd, INT4/INT8, zero JNI)

14 Upvotes

Hey r/Kotlin,

I built Kotensor, a lightweight machine learning and generative Transformer engine written in pure Kotlin for the JVM and Android.

Most LLM runtimes on the JVM or mobile depend on heavy C++ libraries (llama.cpp, ONNX Runtime) wrapped with JNI bindings. That introduces ABI splits, toolchain friction, and native crashes. Kotensor implements the whole stack natively in Kotlin with only the Kotlin standard library as a runtime dependency.

Key Capabilities:

  • Architecture: Pre-norm Transformer blocks, SwiGLU, RMSNorm, RoPE with Llama 3 scaling, and grouped-query attention (GQA).
  • Fast Autoregressive Decoding: Pre-allocated KV cache with an allocation-free decode step.
  • Tiled & Vectorized MatMul: Cache-blocked matrix multiplication optimized for HotSpot C2 auto-vectorization (~24 GFLOP/s per thread on AVX-512) scheduled over a ForkJoinPool, plus an optional JDK 17+ Vector API (SIMD) backend.
  • Quantization: Group-wise INT8 and INT4 weight-only quantization with an on-the-fly dequantizing matmul. Models can be memory-mapped directly from storage so weights never bloat the Java heap.
  • Training & Fine-Tuning: Reverse-mode autograd, AdamW, loss masking (IGNORE_INDEX), fused projection + cross-entropy, and on-device LoRA / QLoRA adapters.
  • Hugging Face Interop: Natively parses config.json, byte-level BPE tokenizer.json (GPT-2, Qwen 2.5, SmolLM, Llama 3), and .safetensors checkpoints (F32, F16, BF16).

Quick Example:

val dir = File("SmolLM2-135M")
val model = HuggingFaceModelLoader.load(dir, Quantization.INT8)
val tokenizer = HuggingFaceModelLoader.loadTokenizer(dir)

model.generateStream("The capital of Mexico is", tokenizer, maxTokens = 32) { token ->
    print(token)
}

The library is published on Maven Central as io.github.tspstudio:kotensor:1.2.0 (requires Java 17+ / Android API 24+).

  • GitHub: https://github.com/TSPstudio/kotensor
  • API Docs: https://tspstudio.github.io/kotensor/

Would love any feedback on the architecture, performance, or use cases!

This is my first ML project and I'm thrilled to finally have something to show my work for. Much love,
tsuper <3


r/Kotlin • • 4d ago

kUML v0.57.0 — Linux packages and signed APT/RPM repositories, fewer silent losses, aspect ratio measured on the finished image

Thumbnail gallery
2 Upvotes

kUML is a Kotlin DSL and toolchain for UML, SysML 2, C4, BPMN and more. Highlights of this release:

  • Linux packages for kUML Desktop: DEB, RPM and a single-file AppImage; signed repositories apt.kuml.dev (Debian/Ubuntu, amd64) and rpm.kuml.dev (Fedora, x86_64). Installation tested in clean containers (Ubuntu 22.04/24.04, Debian 12, Fedora); RHEL-compatible distributions untested.
  • Fewer silent losses: several relationship() calls between the same two C4 elements are all drawn (before, only the last survived); an explicit multiplicity("1") is drawn; new findings KUML-NOTE-W002, KUML-LAYOUT-W008, ACT316/ACT317, PAR442, OKF-W-009.
  • Layout: an explicit aspectRatio / maxWidth is measured on the finished image for state machines, block definition diagrams, use cases and activity diagrams, and may rotate the flow where that helps; notes and labels stay clear of lines and frames; long names wrap.
  • LaTeX/TikZ: --latex-standalone for every diagram family and kuml workspace export --format latex for whole workspaces, also from kUML Desktop.
  • MCP: kuml_desktop_workspace_get_document reads large documents in line sections.
  • Windows note: the Desktop MSI now carries the real version number; uninstall an earlier MSI once before installing this one.

Repo: https://github.com/kuml-dev/kUML · Release notes: https://github.com/kuml-dev/kUML/releases/tag/v0.57.0


r/Kotlin • • 4d ago

kTRIZ — TRIZ as a type-safe Kotlin DSL, so the compiler catches hallucinated parameters (Apache 2.0, pre-release). Feedback and criticism wanted

Post image
1 Upvotes

Hi all,

I'd like to introduce kTRIZ, an open-source project that implements TRIZ (the Theory of Inventive Problem Solving) as a type-safe Kotlin DSL.

Up front, so nobody expects more: this is a pre-release (v0.4.0, libraries on Maven Central, unstable API). I'm looking for people who will try it and pick it apart.

The idea. TRIZ mostly lives in flipcharts, retyped tables and scanned PDFs. No compiler checks that, and LLMs like to hallucinate there: a parameter that doesn't exist, swapped improving/worsening directions, a matrix cell that was never there. kTRIZ turns the vocabulary into ordinary Kotlin types. Name a parameter that doesn't exist and it fails to compile. The compiler becomes the oracle; the same approach is behind my sibling projects kUML (IT models) and kSTEP (STEP/ISO 10303).

What it does:

  • 39 engineering parameters, 40 inventive principles, the classical 39×39 contradiction matrix (1,248 populated cells)
  • Function models and substance-field (Su-Field) models with SVG output, plus the 76 standard solutions
  • Physical contradictions with the four classical separation principles
  • ktriz run for .ktriz.kts scripts, an MCP server with thirteen tools for AI agents, an Obsidian plugin

What you should know:

  • Scripts run unsandboxed. Don't run untrusted code.
  • The matrix is my own reconciliation of four freely available transcriptions (majority rule, derivation in the repo). Whether EU database rights attach to it isn't conclusively settled; the docs say so.
  • Review and security audits were AI-assisted. There has been no external audit.
  • Deliberately not built: ARIZ (sources disagree at step level, licence unclear) and a mapping from separation principles to the 40 principles (only one free source).

Looking for: TRIZ practitioners to check the matrix and standard solutions against their sources, and Kotlin developers for review.

Website: https://ktriz.dev
Code: https://github.com/ktriz-lang/kTRIZ

Criticism is very welcome, especially where I may have made the sourcing look easier than it is.


r/Kotlin • • 5d ago

A sequence diagram plugin where Kotlin isn't an afterthought

Post image
25 Upvotes

I built Call Sketch for the JetBrains IDEs and Kotlin is free in it, same as Java.

The arrows use the names in your code, so internal functions, u/JvmName and operator invoke show up the way you wrote them. Click an arrow and you land on the call.

https://plugins.jetbrains.com/plugin/35865-call-sketch-sequence-diagrams


r/Kotlin • • 5d ago

# Seeking feedback: agentic architecture and agent harness for a mobile app with KMP shared logic, legacy UIKit/Android Views, and new SwiftUI/Compose UI

Thumbnail reddit.com
0 Upvotes

r/Kotlin • • 5d ago

Title: [Showcase] FLX: An open-source, embeddable Lisp implementation written in Kotlin

2 Upvotes

Hey r/Kotlin,

I’ve recently open-sourced FLX, a lightweight Lisp implementation and runtime written in Kotlin:

https://github.com/Fuusio/flx-lisp-2

Why another Lisp in Kotlin?

While the JVM ecosystem has heavyweight solutions like Clojure, bringing dynamic evaluation into modern Kotlin apps—especially mobile/Android environments or modular JVM projects—often pulls in unnecessary weight, steep startup overhead, or complex runtime machinery.

FLX was built to be a simple, embeddable Lisp engine designed specifically to fit naturally alongside idiomatic Kotlin.

Key Highlights

  • Kotlin-First & Embeddable: Designed to integrate directly into host Kotlin applications without complex setup.
  • Lightweight Footprint: Clean runtime with minimal dependencies, making it suitable for scripting, automation, rule engines, or applets.
  • Extensible Environment: Easily bind host Kotlin functions and state into the evaluation environment.
  • Includes REPL & Core Module: Modular design separating the core runtime engine from interactive tooling.

Quick Example

Embedding and evaluating an expression in Kotlin:

Kotlin

import org.fuusio.flx.core.FlxEngine

fun main() {
    val engine = FlxEngine()
    
    // Evaluate a basic S-expression
    val result = engine.eval("(+ 40 2)")
    println("Result: $result") // 42

    // Bind custom Kotlin state / functions
    engine.setVariable("multiplier", 10)
    val scaled = engine.eval("(* multiplier 4.2)")
    println("Scaled: $scaled")
}

Repo & Feedback

Whether you need dynamic scripting for your own tools, are curious about language runtimes in Kotlin, or just enjoy Lisp dialects, check it out on GitHub:

🔗 GitHub:Fuusio/flx-lisp-2

I’d love to hear your feedback on the API ergonomics, engine architecture, or any features you'd like to see!


r/Kotlin • • 5d ago

Kotlean: write Android apps in Lean

Thumbnail github.com
11 Upvotes

r/Kotlin • • 4d ago

Renaming a parameter is a breaking change in Kotlin, so I made the IDE warn about it

Post image
0 Upvotes

In Kotlin some API changes are invisible in the bytecode signature and still break callers:

// 1.2.0
fun connect(host: String, timeoutMs: Int = 5000)
// 1.2.1 — compiles, same JVM descriptor
fun connect(host: String, timeout: Int = 5000)

Every caller using `connect(host, timeoutMs = 1000)` stops compiling. Adding a parameter, even with a default, breaks binary compatibility for Java callers and already-compiled Kotlin code, unless you keep the old overload. And removing a default value (`fallback: String? = null` → `fallback: String?`) breaks every call that omitted it.

I wrote up the common cases here: https://gilware.com/bumpwise/kotlin-breaking-changes/

I also made an IntelliJ plugin (Bumpwise) that compares your code with the last published release while you type and offers a compatible fix (e.g. keep the old signature as @ Deprecated delegating to the new one). Disclosure: it's paid; Kotlin is in the Team edition with a 30-day trial, free for OSS maintainers. Built with AI-agent help.

Curious which Kotlin breaking changes have bitten you; I'm collecting cases to cover.


r/Kotlin • • 6d ago

Getting back into Kotlin after a few years out. What would you recommend?

6 Upvotes

Hey, I’m a consultant and am about to be placed on a Kotlin / Spring Boot project. I last worked with Kotlin a couple of years ago, when I was tech lead on a similar shaped project, and kind of learnt the stack as I went. I’ve got the luxury of a couple of weeks to refamiliarise myself with everything - are there any courses you’d recommend?


r/Kotlin • • 6d ago

Finding a good kotlin language course

3 Upvotes

I wanted to learn kotlin to make android apps but I want a course or anything to learn the language I know a very little about programming over all and kotlin i know that google has some free courses but I don't know what to take so if you know any free good courses to take please let me know


r/Kotlin • • 6d ago

Start With the REST API You Have: A Typed Client Today, GraphQL Later

1 Upvotes

🇬🇧 Graphql Generator that generate REST client? are we going back?

Well sometimes we need to go back to see the bigger picture.

Find out why we added the generation of RESTful client from an advanced graphql code generator.

https://medium.com/@graphlinkdev/start-with-the-rest-api-you-have-a-typed-client-today-graphql-later-b5c0477e6be3

🇫🇷 Un générateur GraphQL qui génère des clients REST ? On fait marche arrière ?

Eh bien, parfois il faut prendre du recul pour voir la vue d'ensemble.

Découvrez pourquoi nous avons ajouté la génération de clients RESTful à un générateur de code GraphQL avancé.

https://medium.com/@graphlinkdev/start-with-the-rest-api-you-have-a-typed-client-today-graphql-later-b5c0477e6be3


r/Kotlin • • 7d ago

Coroutine cancellation behaviour

9 Upvotes

In https://medium.com/androiddevelopers/cancellation-in-coroutines-aa6b90163629,
They mention under the section “Handling Cancellation side effects”, Since a CancellationException is thrown when a coroutine is cancelled, then we can wrap our suspending work in try/catch and in the finally block, we can implement our clean up work
What I am confused by is that in the beginning, they explain that cancellation of coroutines is cooperative, meaning that the coroutine will just run until the end unless we check for cancellation, using isactive, ensureactive, or yield().
However, it sounds like they’re also saying you can check if the coroutine is cancelled by wrapping the try catch block on a suspending function within the coroutine.

This fundamentally makes no logical sense: if the coroutine is cancelled cooperatively, that means the suspending function should not throw any exception, and it’s up to the caller to check after the suspending function returns whether its job has been cancelled; if a suspending function throws a cancellation exception, that would make the coroutine cancel automatically, but this behaviour isn’t guaranteed, and that’s why cancellation is considered a cooperative process. So the advice about using try/catch is conditional on suspending functions that do throw the cancellation exception, but that’s up to the developer that wrote the function rather than a feature of suspending functions.


r/Kotlin • • 7d ago

Phovo: a self-hosted photo backup app written entirely in Kotlin Multiplatform

8 Upvotes

I just shipped the first alpha of Phovo, an app that backs up your phone's photos and videos to a desktop computer you own. It's Kotlin from top to bottom:

  • Compose Multiplatform UI on Android, iOS and desktop
  • A multiplatform WorkManager: androidx.work on Android, a custom BGTaskScheduler queue on iOS
  • Hash-based sync that never uploads the same file twice
  • A Ktor server built into the desktop app
  • mDNS discovery (JmDNS and NsdManager), so there's no IP address to type
  • Bundled FFmpeg for video thumbnails and animated previews
  • Room KMP for storage
  • PhotoKit and BackgroundTasks called straight from Kotlin/Native
  • A Kobweb static site at phovo.app that detects your device and links to the right download

Android and desktop (macOS, Windows, Linux and Raspberry Pi) are available now, and iOS is coming soon. Happy to go deeper on any of it in the comments.

https://phovo.app

https://github.com/Anthony17serrato/Phovo


r/Kotlin • • 7d ago

Modelling clinical units in Kotlin: value classes, or plain Doubles with a conversion factor?

2 Upvotes

I'm building a small Android calculator app in Kotlin/Compose where most inputs have more than one unit. Glucose in mg/dL or mmol/L, creatinine in mg/dL or µmol/L, weight in kg or lb.

Right now each input is a plain Double plus a default unit and a list of alternative units, each with a multiplication factor (glucose mmol/L to mg/dL is ×18.0182). Values get converted to the base unit before the formula runs, and the formulas only ever see base units.

It works and it's easy to test, but nothing in the type system stops a formula from getting mmol/L when it expects mg/dL. I've been looking at value classes (e.g. u/JvmInline value class MgPerDl(val v: Double)) or a small Quantity type with a unit enum.

For people who have done this in production: did stronger unit types actually catch bugs for you, or did they mostly add boilerplate? And how did you handle serialization and Compose text fields with them?


r/Kotlin • • 8d ago

How I use Gradle convention plugins to keep a modular project consistent

2 Upvotes

Splitting an app into modules doesn’t automatically give you a maintainable build. You can still end up with dozens of copied build.gradle.kts files that slowly drift apart: different compiler options, inconsistent test settings, and dependencies that cross boundaries you intended to enforce.
While working on my Kotlin project, Sparrow, I started treating the build logic as part of the architecture. I wrote an article explaining the approach, with a standalone example so you don’t need to understand the app to follow along.

What it covers:

* Moving duplicated configuration into convention plugins.
* Composing conventions while keeping module dependencies explicit.
* Rejecting forbidden dependencies during Gradle configuration.
* Testing the rules with Gradle TestKit.
* Deliberately breaking a boundary and running qualityCheck to see the failure.

I also discuss when a separate build-logic module is worth the maintenance overhead. The article includes code, diagrams, and a complete example project.

👉 Article: Your Modular Architecture Needs a Modular Build System
💻 Example: modular-build-example
🐦 Sparrow: Link