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.
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
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
| Client | Support | Installed as |
|---|---|---|
| Claude Code | Native | .claude/skills/<id>/SKILL.md |
| OpenAI Codex | Adapter | .codex/skills/<id>/SKILL.md |
| Cursor | Adapter | .cursor/rules/<id>.mdc |
| VS Code (Copilot) | Adapter | .github/instructions/<id>.instructions.md |
| Generic markdown | Adapter | docs/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
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) orcheckNotNull(illegal state). - Return early with
?: return/?: continueinstead of nestingif (x != null). - Smart casts only work on
val, localvarnot 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 varonly for DI/lifecycle-injected members; useby lazyfor expensive read-only values. Neverlateinita 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 interfacefor closed hierarchies;enum classwhen 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 classfor values: onlyvals, copy for updates, no inheritance. Publicdata classin a library is an ABI trap (copy/componentN); useexplicitApi()and consider a plain class.- Prefer
Result-like sealed types or exceptions with intent; do not returnPair/Tripleacross module APIs, name the type.
3. Coroutines
| Need | Use |
|---|---|
| Parallel independent calls | coroutineScope { val a = async { f() }; val b = async { g() }; a.await() to b.await() } |
| Failure of one child must not cancel siblings | supervisorScope { } |
| Switch dispatcher | withContext(Dispatchers.IO) { } inside the suspend function that does the blocking work (callers stay main-safe) |
| Timeout | withTimeout(5.seconds) / withTimeoutOrNull |
| Wrap a callback API | suspendCancellableCoroutine { cont -> ...; cont.invokeOnCancellation { cancel() } } |
- Structured concurrency: launch only in a scope with a lifecycle (
viewModelScope,lifecycleScope, an injectedCoroutineScope).GlobalScopeis a leak. - Never swallow
CancellationException.catch (e: Exception)around suspend calls must rethrow it (catch (e: CancellationException) { throw e }) or catch narrower types.runCatchinghas the same trap. - Inject dispatchers (
class Repo(private val io: CoroutineDispatcher)) so tests can passStandardTestDispatcher. Never hard-codeDispatchers.IOin testable classes. Dispatchers.Defaultfor CPU work,IOfor blocking I/O,Main.immediatefor UI. Do not callrunBlockingon a UI or request thread.- Check
ensureActive()/yield()in long CPU loops so cancellation is honoured.
4. Flow
- Cold
Flowfor streams (DB, network);StateFlowfor state (always has a value, conflated, equality-compared);SharedFlowfor events (configurereplay/extraBufferCapacity). One-shot events: prefer modelling as state; otherwiseChannel(BUFFERED)+receiveAsFlow(). - Expose
StateFlow(notMutableStateFlow) from ViewModels; convert withstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial). - Collect on Android with
collectAsStateWithLifecycle()(Compose) orrepeatOnLifecycle(STARTED); plainlifecycleScope.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). Nevercollectinsidecollect. - Do not
emitfrom a different context than the collector's insideflow {}; useflowOnorchannelFlow.
5. Scope functions
| Fn | Receiver | Returns | Use for |
|---|---|---|---|
let | it | lambda result | null-check chains, mapping a value (x?.let { use(it) }) |
apply | this | receiver | configuring an object after construction |
also | it | receiver | side effects (logging) in a chain |
run | this | lambda result | compute a value from an object/scope |
with | this | lambda result | several 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 viabuildList { }/buildMap { }. Never exposeMutableListfrom 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/groupByinstead of repeatedfindin loops (O(n^2)).map.getOrPut(k) { },map.getValue(k)when absence is a bug.- Strings:
buildString, templates"$a-${b.c}", raw strings withtrimIndent().
7. Idioms
- Expression bodies,
whenas expression, named arguments for booleans/same-typed params, default arguments instead of overloads (@JvmOverloadsonly for Java callers). - Extension functions for domain helpers; keep them in the file/module that owns the type and avoid extending
String/Anyglobally. objectfor stateless singletons;companion objectonly for factories/constants;const valfor compile-time constants.use { }forCloseable;check/requirefor preconditions;error("...")for unreachable states.@Throwsonly when Java/Swift callers need it.- Serialization:
kotlinx.serializationwith@Serializable,Json { ignoreUnknownKeys = true }; never reflection-based parsing on hot paths.
Common mistakes
catch (e: Exception)/runCatchingaround suspend code eating cancellation.GlobalScope.launch.runBlockingin production code paths.var+ mutable collections indata classes used as UI state.!!to silence the compiler.lateinitfor nullable data.whenwithelse ->on a sealed type (hides new subclasses). UsingPairwhere a named type belongs.- Collecting a
StateFlowinlifecycleScope.launchwithoutrepeatOnLifecycle. Launching coroutines ininit {}that capturethisbefore construction completes. - Reading
Dispatchers.Mainin unit tests withoutDispatchers.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.