| name | kotlin-convention |
| description | Writes idiomatic, clean Kotlin following Android conventions. Use when user asks for "Kotlin code review", "is this idiomatic Kotlin", "Kotlin style check", "how to write this in Kotlin", or to "follow Kotlin best practices". |
Kotlin Convention
Overview
This skill defines idiomatic Kotlin conventions for Android projects: naming, null safety, data modeling, functional patterns, and language features to embrace or avoid.
Naming
| Element | Convention | Example |
|---|
| Class / Interface / Object | PascalCase | OrderRepository, UserMapper |
| Function / Variable | camelCase | fetchUser(), currentState |
Constant (const val, object val) | SCREAMING_SNAKE_CASE | MAX_RETRY_COUNT |
| Package | lowercase, dot-separated | com.example.feature.order |
| Extension function | camelCase, descriptive | String.isValidEmail() |
| Test function | backtick sentence | `SHOULD return error WHEN network fails` |
Naming Rules
- Be explicit over short:
userIdentifier not uid
- Boolean properties: prefix with
is, has, can → isLoading, hasError
- Functions returning
Boolean: prefix with is, can, should → isValid(), canSubmit()
- Avoid
data, info, manager as suffixes unless unavoidable
Null Safety
Avoid !!
val name = user!!.name
val name = user?.name ?: "Unknown"
fun process(user: User?) {
val u = user ?: return
doWork(u)
}
Prefer let, run, apply, also, with Appropriately
| Function | Receiver | Returns | Best For |
|---|
let | it | lambda result | Null checks, transformation |
run | this | lambda result | Object configuration + result |
apply | this | receiver | Builder-style setup |
also | it | receiver | Side effects (logging) |
with | this | lambda result | Multiple calls on same object |
user?.let { sendEmail(it.email) }
val config = Config().apply {
host = "api.example.com"
port = 443
timeout = 30
}
return fetchUser(id).also { log("Fetched user: $it") }
Data Classes
data class Order(
val id: String,
val items: List<OrderItem>,
val status: OrderStatus,
val createdAt: Instant,
)
val updated = order.copy(status = OrderStatus.SHIPPED)
data class Order(
var id: String,
var status: String,
)
Sealed Classes / Interfaces
Use for restricted hierarchies — states, results, events:
sealed interface Result<out T> {
data class Success<T>(val value: T) : Result<T>
data class Error(val exception: Throwable) : Result<Nothing>
data object Loading : Result<Nothing>
}
sealed interface UiEvent {
data object OnScreenOpened : UiEvent
data class OnItemClicked(val id: String) : UiEvent
}
when (result) {
is Result.Success -> show(result.value)
is Result.Error -> showError(result.exception)
Result.Loading -> showLoading()
}
Prefer sealed interface over sealed class — more flexible (multiple inheritance).
Functions
Single Expression Functions
fun Double.toPercentage(): String = "${(this * 100).toInt()}%"
fun Double.toPercentage(): String {
return "${(this * 100).toInt()}%"
}
Extension Functions
fun Instant.isOlderThan(duration: Duration): Boolean = this < Clock.System.now() - duration
fun String.isValidEmail(): Boolean = android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
fun String.doOrderThing(): Order { ... }
Default Parameters vs Overloads
fun fetchOrders(userId: String, pageSize: Int = 20, page: Int = 0): List<Order>
fun fetchOrders(userId: String): List<Order>
fun fetchOrders(userId: String, pageSize: Int): List<Order>
fun fetchOrders(userId: String, pageSize: Int, page: Int): List<Order>
Collections
val items: List<Item> = listOf()
val mutable: MutableList<Item> = mutableListOf()
val activeUsers = users
.filter { it.isActive }
.sortedByDescending { it.lastLogin }
.take(10)
val result = largeList
.asSequence()
.filter { it.isValid }
.map { transform(it) }
.firstOrNull()
val byCategory = products.groupBy { it.category }
val userById: Map<String, User> = users.associateBy { it.id }
val (active, inactive) = users.partition { it.isActive }
Value Classes (Inline)
Prevent primitive type confusion at zero runtime cost:
@JvmInline value class UserId(val value: String)
@JvmInline value class ProductId(val value: String)
@JvmInline value class Price(val cents: Long) {
val euros: Double get() = cents / 100.0
}
fun getUser(id: UserId): User
fun getProduct(id: ProductId): Product
Error Handling
suspend fun fetchData(): Result<Data> = runCatching { api.getData() }
require(count >= 0) { "Count must be non-negative, got $count" }
check(isInitialized) { "Must call init() before use" }
error("Unexpected branch in ${::processState.name}")
try {
val user = fetchUser(id)
} catch (e: UserNotFoundException) {
}
Coroutines Style
suspend fun fetchUser(id: String): User
viewModelScope.launch(CoroutineName("load-orders")) { ... }
fun getUser(): User = runBlocking { fetchUser("1") }
When Expressions
val label = when (status) {
Status.PENDING -> "Pending"
Status.ACTIVE -> "Active"
Status.CLOSED -> "Closed"
}
when {
age < 0 -> error("Invalid age")
age < 18 -> showMinorWarning()
age >= 65 -> offerSeniorDiscount()
else -> processStandard()
}
Object / Companion Object
class Config private constructor(val host: String, val port: Int) {
companion object {
val DEFAULT = Config("localhost", 8080)
fun fromEnv() = Config(
host = System.getenv("HOST") ?: "localhost",
port = System.getenv("PORT")?.toInt() ?: 8080,
)
}
}
object DateFormatter {
private val formatter = DateTimeFormatter.ISO_LOCAL_DATE
fun format(date: LocalDate): String = formatter.format(date)
}
Anti-Patterns
| ❌ Avoid | ✅ Instead |
|---|
!! operator | Safe call + Elvis / early return |
var in data classes | val + copy() |
| Checked exceptions | Result<T> / sealed error types |
| Java-style overloads | Default parameter values |
Nested if chains | when expression / guard returns |
Any as parameter type | Specific sealed interface / generics |
| Magic numbers | Named constants / value classes |
Mutable List exposed publicly | List (immutable) in public API |
lateinit var for nullable types | Nullable with ? or by lazy { } — lateinit is only valid for non-null, and crashes with UninitializedPropertyAccessException if accessed before init |
Checklist: Code Review
References