Skip to content
DevBuildKit
AgentsSkillsCommandsPacksPricingDocsBlogTools
Log inGet DevBuildKit

Kotlin

Idiomatic, safe Kotlin — null-safety, sealed types, coroutines and Flow, scope functions, collections and sequences, value classes, and the pitfalls that cause crashes and leaks.

SkillFreev1.0.0
  1. Skills
  2. Kotlin

What it does

Idiomatic, safe Kotlin — null-safety, sealed types, coroutines and Flow, scope functions, collections and sequences, value classes, and the pitfalls that cause crashes and leaks.

Category
languagemobilebackend
Platforms
androidjvmbackend
Frameworks and tools
kotlincoroutineskotlinx-serialization
Capabilities
code-generationreviewrefactoring

Example tasks

  • “Refactor a callback-based repository into suspend functions and Flow with correct cancellation.”
  • “Model a network result as a sealed interface and handle it exhaustively in the ViewModel.”
  • “Review a Kotlin file for null-safety, scope function misuse and collection performance issues.”

Works with

Recommended alongside

  • Android Architecture· skill
  • Jetpack Compose· skill
  • Clean Code· skill

Used by

  • Android Architect
  • Android Build Engineer
  • Android Performance Engineer
  • Android Test Engineer
  • Compose Specialist
  • Kotlin Specialist
  • /android-fix-build
  • /android-test

Permissions summary

  • Files

    Reads files only

  • Shell

    No shell commands

  • Network

    No network

Permissions are declared in the component manifest and compiled into each client's tool list. Components are built for least privilege.

Supported environments

ClientSupportInstalled as
Claude CodeNative.claude/skills/<id>/SKILL.md
OpenAI CodexAdapter.codex/skills/<id>/SKILL.md
CursorAdapter.cursor/rules/<id>.mdc
VS Code (Copilot)Adapter.github/instructions/<id>.instructions.md
Generic markdownAdapterdocs/forgekit/skills/<id>.md

Claude Code is the native reference. Other clients use adapters, so behaviour is close but not identical. See the compatibility matrix.

Included in packs

  • android

Full skill (free preview)

This is a free component, so its complete content is public. It is exactly what gets installed (before client-specific formatting).

Kotlin

Apply these rules when writing or reviewing Kotlin (Android, JVM backend or multiplatform). Check the project's Kotlin version and kotlinOptions/compilerOptions (-Werror, explicitApi(), K2) before using newer language features.

1. Null-safety

  • Model absence with T?; never use !! outside tests. Prefer ?., ?:, requireNotNull(x) { "message" } (programmer error) or checkNotNull (illegal state).
  • Return early with ?: return / ?: continue instead of nesting if (x != null).
  • Smart casts only work on val, local var not captured by a mutating lambda, and same-module properties without custom getters. Otherwise bind first: val name = user.name ?: return.
  • Platform types (String!) from Java: annotate at the boundary (@Nullable/@NonNull) or declare the Kotlin type explicitly (val s: String? = javaCall()).
  • lateinit var only for DI/lifecycle-injected members; use by lazy for expensive read-only values. Never lateinit a value that can legitimately be absent.

2. Types that make illegal states unrepresentable

sealed interface UiState<out T> {
    data object Loading : UiState<Nothing>
    data class Success<T>(val data: T) : UiState<T>
    data class Error(val cause: Throwable, val retryable: Boolean) : UiState<Nothing>
}
fun render(s: UiState<List<Item>>) = when (s) {   // no else: compiler enforces exhaustiveness
    UiState.Loading -> showSpinner()
    is UiState.Success -> show(s.data)
    is UiState.Error -> showError(s.cause)
}
  • sealed interface for closed hierarchies; enum class when entries carry no per-instance data shape; data object (Kotlin 1.9+) for singletons in sealed trees.
  • @JvmInline value class UserId(val raw: String) to stop primitive mix-ups (id vs id). Boxed when nullable/generic - don't use in hot collections.
  • data class for values: only vals, copy for updates, no inheritance. Public data class in a library is an ABI trap (copy/componentN); use explicitApi() and consider a plain class.
  • Prefer Result-like sealed types or exceptions with intent; do not return Pair/Triple across module APIs, name the type.

3. Coroutines

NeedUse
Parallel independent callscoroutineScope { val a = async { f() }; val b = async { g() }; a.await() to b.await() }
Failure of one child must not cancel siblingssupervisorScope { }
Switch dispatcherwithContext(Dispatchers.IO) { } inside the suspend function that does the blocking work (callers stay main-safe)
TimeoutwithTimeout(5.seconds) / withTimeoutOrNull
Wrap a callback APIsuspendCancellableCoroutine { cont -> ...; cont.invokeOnCancellation { cancel() } }
  • Structured concurrency: launch only in a scope with a lifecycle (viewModelScope, lifecycleScope, an injected CoroutineScope). GlobalScope is a leak.
  • Never swallow CancellationException. catch (e: Exception) around suspend calls must rethrow it (catch (e: CancellationException) { throw e }) or catch narrower types. runCatching has the same trap.
  • Inject dispatchers (class Repo(private val io: CoroutineDispatcher)) so tests can pass StandardTestDispatcher. Never hard-code Dispatchers.IO in testable classes.
  • Dispatchers.Default for CPU work, IO for blocking I/O, Main.immediate for UI. Do not call runBlocking on a UI or request thread.
  • Check ensureActive()/yield() in long CPU loops so cancellation is honoured.

4. Flow

  • Cold Flow for streams (DB, network); StateFlow for state (always has a value, conflated, equality-compared); SharedFlow for events (configure replay/extraBufferCapacity). One-shot events: prefer modelling as state; otherwise Channel(BUFFERED) + receiveAsFlow().
  • Expose StateFlow (not MutableStateFlow) from ViewModels; convert with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial).
  • Collect on Android with collectAsStateWithLifecycle() (Compose) or repeatOnLifecycle(STARTED); plain lifecycleScope.launch { flow.collect } keeps collecting in the background.
  • Operators: flatMapLatest (cancel previous, e.g. search), debounce, distinctUntilChanged, combine, catch { emit(fallback) } (only catches upstream), flowOn (changes upstream only). Never collect inside collect.
  • Do not emit from a different context than the collector's inside flow {}; use flowOn or channelFlow.

5. Scope functions

FnReceiverReturnsUse for
letitlambda resultnull-check chains, mapping a value (x?.let { use(it) })
applythisreceiverconfiguring an object after construction
alsoitreceiverside effects (logging) in a chain
runthislambda resultcompute a value from an object/scope
withthislambda resultseveral calls on a non-null object

Do not nest more than two levels; if it/this is ambiguous, name the lambda parameter or use a plain val.

6. Collections and performance

  • Use List/Map/Set (read-only) in APIs; mutate only locally via buildList { }/buildMap { }. Never expose MutableList from a class.
  • Chained operators on big collections allocate an intermediate list per step: use .asSequence() when there are 2+ chained operators and the data is large or short-circuiting (first, take). For small lists, plain operators are faster.
  • associateBy/groupBy instead of repeated find in loops (O(n^2)). map.getOrPut(k) { }, map.getValue(k) when absence is a bug.
  • Strings: buildString, templates "$a-${b.c}", raw strings with trimIndent().

7. Idioms

  • Expression bodies, when as expression, named arguments for booleans/same-typed params, default arguments instead of overloads (@JvmOverloads only for Java callers).
  • Extension functions for domain helpers; keep them in the file/module that owns the type and avoid extending String/Any globally.
  • object for stateless singletons; companion object only for factories/constants; const val for compile-time constants.
  • use { } for Closeable; check/require for preconditions; error("...") for unreachable states. @Throws only when Java/Swift callers need it.
  • Serialization: kotlinx.serialization with @Serializable, Json { ignoreUnknownKeys = true }; never reflection-based parsing on hot paths.

Common mistakes

  • catch (e: Exception) / runCatching around suspend code eating cancellation. GlobalScope.launch. runBlocking in production code paths.
  • var + mutable collections in data classes used as UI state. !! to silence the compiler. lateinit for nullable data.
  • when with else -> on a sealed type (hides new subclasses). Using Pair where a named type belongs.
  • Collecting a StateFlow in lifecycleScope.launch without repeatOnLifecycle. Launching coroutines in init {} that capture this before construction completes.
  • Reading Dispatchers.Main in unit tests without Dispatchers.setMain(testDispatcher).

Version and changelog

Latest version 1.0.0. Requires DevBuildKit CLI 1.0.0 or newer.

Changelog — Kotlin

1.0.0

  • Initial release.

Build with this skill

Create Demo Project

Install in CLI

$ devbuild add skill kotlin

Dependencies are resolved automatically.

Free. Needs a free account: run devbuild login once.

IDkotlin
Version1.0.0
TierFree
DevBuildKit

Your entire AI development team. One install.

DevBuildKit never uploads your source code. Telemetry is opt-in and anonymous.

Product

  • Agents
  • Skills
  • Commands
  • Packs
  • Features
  • Live demo
  • Pricing

Learn

  • Documentation
  • Getting started
  • CLI reference
  • Blog
  • Changelog
  • Compare

Free tools

  • All tools
  • Agent generator
  • Config converter
  • Stack detector
  • Context analyzer

Use cases

  • Android development
  • iOS development
  • SaaS development
  • Backend development
  • App Factory
  • Game development

Company

  • Terms
  • Privacy
  • Refunds
  • Log in
  • Sign up

© 2026 DevBuildKit. All rights reserved.

DevBuildKit is an independent product. Claude, Claude Code, Anthropic, OpenAI, Codex, ChatGPT, Cursor, Visual Studio Code, GitHub Copilot, Microsoft and all other product names are trademarks of their respective owners. DevBuildKit is not affiliated with, endorsed by or sponsored by any of them; names are used only to describe compatibility.