Automated summary
Provides Kotlin and Android development guidance for Gradle/Compose projects, covering build configuration, null safety, sealed classes, data/value classes, and error handling.
Strengths
- Includes complete Gradle Kotlin DSL and version catalog setup for a Compose app.
- Shows idiomatic Kotlin patterns such as safe calls, Elvis operators, sealed results, and value classes.
- Keeps examples concise and directly reusable in Android projects.
Limitations
- The provided content stops before expanding the coroutines and state-management topics mentioned in the description.
- Tied to Android and specific tool versions, so guidance can age as AGP, Kotlin, and Compose versions change.
- Does not cover testing, architecture, or migration strategies in depth.
Use when scaffolding or writing Kotlin Android code with Gradle Kotlin DSL and Jetpack Compose.
Avoid for non-Android Kotlin work, such as backend services, or when you need current version-specific migration advice.
Security analysis
SafeThe skill is purely instructional Kotlin/Android documentation. The declared Bash usage is limited to standard Gradle commands (build, test, lint, clean) executed in the developer's own project; nothing exfiltrates data, decodes payloads, disables safety mechanisms, or touches destructive paths. The only inherent risk is that `./gradlew` runs project-local build scripts, which is the normal and expected Android development workflow.
- •Declares Bash, Write, and Edit, but all listed shell usage is standard Gradle build/test/lint invocations; no destructive, obfuscated, or network-exfiltration instructions present.
- •Example code includes a not-null assertion (`user!!.name`), flagged in-text as 'use sparingly' — a code-quality nit, not a skill-level risk.
Examples
Create a new Android app in Kotlin with Gradle Kotlin DSL, a version catalog, Jetpack Compose, minSdk 26, and targetSdk 35.Refactor this Kotlin function to return a sealed Result type and handle Success, Error, and Loading exhaustively in a when expression.Set up settings.gradle.kts, build.gradle.kts, and libs.versions.toml for a Compose Android app using Kotlin 2.0.0 and AGP 8.5.0.name: kotlin description: Write Kotlin code for Android following best practices. Use when developing with Jetpack Compose, Android SDK, or Kotlin projects. Covers coroutines, state management, and tooling. allowed-tools: Read, Write, Edit, Bash, Glob, Grep
Kotlin / Android Development
Project Setup
Gradle Kotlin DSL
// settings.gradle.kts
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "MyApp"
include(":app")
build.gradle.kts (app)
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "com.example.myapp"
compileSdk = 35
defaultConfig {
applicationId = "com.example.myapp"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "1.0"
}
buildFeatures {
compose = true
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.material3)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
}
Version Catalog (libs.versions.toml)
[versions]
kotlin = "2.0.0"
compose-bom = "2024.06.00"
lifecycle = "2.8.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version = "1.13.1" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "compose-bom" }
[plugins]
android-application = { id = "com.android.application", version = "8.5.0" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
Type Patterns
Null Safety
// Safe call operator
val length = name?.length
// Elvis operator
val displayName = user?.name ?: "Guest"
// Safe cast
val number = value as? Int
// Not-null assertion (use sparingly)
val name = user!!.name
// let for null checks
user?.let { safeUser ->
println(safeUser.name)
}
Sealed Classes
sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val exception: Throwable) : Result<Nothing>()
data object Loading : Result<Nothing>()
}
// Exhaustive when
fun handleResult(result: Result<User>) = when (result) {
is Result.Success -> showUser(result.data)
is Result.Error -> showError(result.exception)
Result.Loading -> showLoading()
}
Data Classes
data class User(
val id: String,
val email: String,
val name: String,
val createdAt: Instant = Instant.now()
)
// Copy with modifications
val updatedUser = user.copy(name = "New Name")
// Destructuring
val (id, email, name) = user
Value Classes
@JvmInline
value class UserId(val value: String)
@JvmInline
value class Email(val value: String) {
init {
require(value.contains("@")) { "Invalid email" }
}
}
Error Handling
Result Type
fun parseNumber(input: String): Result<Int> {
return try {
Result.success(input.toInt())
} catch (e: NumberFormatException) {
Result.failure(e)
}
}
// Usage
parseNumber("123")
.onSuccess { number -> println("Parsed: $number") }
.onFailure { error -> println("Error: ${error.message}") }
// Transform
val doubled = parseNumber("42")
.map { it * 2 }
.getOrDefault(0)
runCatching
val result = runCatching {
riskyOperation()
}.getOrElse { error ->
logError(error)
defaultValue
}
// Chain operations
runCatching { fetchUser(id) }
.mapCatching { user -> processUser(user) }
.onSuccess { result -> display(result) }
.onFailure { error -> showError(error) }
Coroutines
Basic Coroutines
// Suspend function
suspend fun fetchUser(id: String): User {
return withContext(Dispatchers.IO) {
api.getUser(id)
}
}
// Launch coroutine
viewModelScope.launch {
try {
val user = fetchUser("123")
_uiState.value = UiState.Success(user)
} catch (e: Exception) {
_uiState.value = UiState.Error(e.message)
}
}
Flow
// Create flow
fun observeUsers(): Flow<List<User>> = flow {
while (true) {
emit(repository.getUsers())
delay(5000)
}
}.flowOn(Dispatchers.IO)
// Collect flow
viewModelScope.launch {
observeUsers()
.catch { e -> emit(emptyList()) }
.collect { users ->
_users.value = users
}
}
StateFlow
class UserViewModel : ViewModel() {
private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
fun loadUser(id: String) {
viewModelScope.launch {
_uiState.value = UiState.Loading
try {
val user = repository.getUser(id)
_uiState.value = UiState.Success(user)
} catch (e: Exception) {
_uiState.value = UiState.Error(e.message ?: "Unknown error")
}
}
}
}
Jetpack Compose
Basic Composable
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello, $name!",
modifier = modifier.padding(16.dp),
style = MaterialTheme.typography.headlineMedium
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
MyAppTheme {
Greeting("Android")
}
}
State Management
@Composable
fun Counter() {
var count by remember { mutableIntStateOf(0) }
Column(
modifier = Modifier.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Count: $count",
style = MaterialTheme.typography.headlineMedium
)
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = { count++ }) {
Text("Increment")
}
}
}
ViewModel Integration
@Composable
fun UserScreen(
viewModel: UserViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
when (val state = uiState) {
is UiState.Loading -> CircularProgressIndicator()
is UiState.Success -> UserContent(state.user)
is UiState.Error -> ErrorMessage(state.message)
}
}
@Composable
fun UserContent(user: User) {
Column(modifier = Modifier.padding(16.dp)) {
Text(user.name, style = MaterialTheme.typography.titleLarge)
Text(user.email, style = MaterialTheme.typography.bodyMedium)
}
}
Side Effects
@Composable
fun UserDetailScreen(userId: String, viewModel: UserViewModel = hiltViewModel()) {
// Run once when userId changes
LaunchedEffect(userId) {
viewModel.loadUser(userId)
}
// Run on every recomposition
SideEffect {
analytics.trackScreen("UserDetail")
}
// Cleanup when leaving composition
DisposableEffect(Unit) {
val listener = viewModel.addListener()
onDispose {
listener.remove()
}
}
}
Testing
Unit Tests (JUnit 5)
class UserViewModelTest {
@Test
fun `loadUser updates state to success`() = runTest {
val repository = mockk<UserRepository>()
coEvery { repository.getUser("123") } returns User("123", "test@example.com")
val viewModel = UserViewModel(repository)
viewModel.loadUser("123")
assertEquals(
UiState.Success(User("123", "test@example.com")),
viewModel.uiState.value
)
}
@Test
fun `loadUser updates state to error on failure`() = runTest {
val repository = mockk<UserRepository>()
coEvery { repository.getUser(any()) } throws IOException("Network error")
val viewModel = UserViewModel(repository)
viewModel.loadUser("123")
assertTrue(viewModel.uiState.value is UiState.Error)
}
}
Compose UI Tests
class UserScreenTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun displaysUserName() {
val user = User("1", "test@example.com", "John Doe")
composeTestRule.setContent {
MyAppTheme {
UserContent(user = user)
}
}
composeTestRule.onNodeWithText("John Doe").assertIsDisplayed()
composeTestRule.onNodeWithText("test@example.com").assertIsDisplayed()
}
@Test
fun buttonClickIncrementsCounter() {
composeTestRule.setContent {
MyAppTheme {
Counter()
}
}
composeTestRule.onNodeWithText("Count: 0").assertIsDisplayed()
composeTestRule.onNodeWithText("Increment").performClick()
composeTestRule.onNodeWithText("Count: 1").assertIsDisplayed()
}
}
Tooling
# Build
./gradlew build
./gradlew assembleDebug
./gradlew assembleRelease
# Run tests
./gradlew test # Unit tests
./gradlew connectedAndroidTest # Instrumented tests
# Linting
./gradlew detekt # Code smells
./gradlew ktlintCheck # Style check
./gradlew ktlintFormat # Auto-fix style
# Code analysis
./gradlew lint # Android Lint
# Clean
./gradlew clean
detekt.yml
build:
maxIssues: 0
complexity:
LongMethod:
threshold: 30
ComplexCondition:
threshold: 4
style:
MaxLineLength:
maxLineLength: 120
WildcardImport:
active: true
naming:
FunctionNaming:
functionPattern: '[a-z][a-zA-Z0-9]*'
.editorconfig (ktlint)
[*.{kt,kts}]
indent_size = 4
max_line_length = 120
ktlint_code_style = android_studio
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/kotlin-android-development-mmlj2nyh/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/kotlin-android-development-mmlj2nyh' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/kotlin-android-development-mmlj2nyh/download' --output '.skill-downloads/kotlin-android-development-mmlj2nyh/SKILL.md.part' && mv '.skill-downloads/kotlin-android-development-mmlj2nyh/SKILL.md.part' '.skill-downloads/kotlin-android-development-mmlj2nyh/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
Tools declared by the author (check availability in your agent): Read, Write, Edit, Bash, Glob, Grep
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/kotlin-android-development-mmlj2nyh/SKILL.md' && test -s '.skill-downloads/kotlin-android-development-mmlj2nyh/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/kotlin' && cp -R '.skill-downloads/kotlin-android-development-mmlj2nyh' '.claude/skills/kotlin'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/kotlin-android-development-mmlj2nyh'openskills read 'kotlin-android-development-mmlj2nyh'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/kotlin-android-development-mmlj2nyh/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
React Hook Form Best Practices
Development
Master React Hook Form: avoid anti-patterns, manage subscriptions, and handle reset, dirty state, and controlled inputs correctly.
Emotion to Mantine Migration
Development
Migrate Emotion styled-components to Mantine components with style props and CSS modules. Use when converting .styled.tsx files or removing @emotion imports.
Scope Creep Detector
Development
Analyzes git diffs against a stated intent to detect scope creep, unrelated files, broad PRs, and oversized changes, then suggests keep, split, or justify actions.