kotlin-patterns

kotlin-patterns

熱門

慣用的 Kotlin 模式、最佳實務與慣例,用於建構穩健、高效且易於維護的 Kotlin 應用程式,包含協程、空值安全與 DSL 建構器。

23萬星標
3.5萬分支
更新於 2026/7/17
SKILL.md
readonlyread-only
name
kotlin-patterns
description

慣用的 Kotlin 模式、最佳實務與慣例,用於建構穩健、高效且易於維護的 Kotlin 應用程式,包含協程、空值安全與 DSL 建構器。

Kotlin 開發模式

慣用的 Kotlin 模式與最佳實務,用於建構穩健、高效且易於維護的應用程式。

使用時機

  • 撰寫新的 Kotlin 程式碼
  • 審查 Kotlin 程式碼
  • 重構現有 Kotlin 程式碼
  • 設計 Kotlin 模組或函式庫
  • 配置 Gradle Kotlin DSL 建置

運作方式

此技能在七個關鍵領域強制執行慣用的 Kotlin 慣例:使用型別系統與安全呼叫運算子的空值安全、透過 valcopy() 在資料類別上實現不可變性、用於窮舉型別階層的密封類別與介面、使用協程與 Flow 的結構化並行、用於在不使用繼承的情況下新增行為的擴充函式、使用 @DslMarker 與 lambda 接收者的型別安全 DSL 建構器,以及用於建置配置的 Gradle Kotlin DSL。

範例

使用 Elvis 運算子的空值安全:

fun getUserEmail(userId: String): String {
    val user = userRepository.findById(userId)
    return user?.email ?: "unknown@example.com"
}

用於窮舉結果的密封類別:

sealed class Result<out T> {
    data class Success<T>(val data: T) : Result<T>()
    data class Failure(val error: AppError) : Result<Nothing>()
    data object Loading : Result<Nothing>()
}

使用 async/await 的結構化並行:

suspend fun fetchUserWithPosts(userId: String): UserProfile =
    coroutineScope {
        val user = async { userService.getUser(userId) }
        val posts = async { postService.getUserPosts(userId) }
        UserProfile(user = user.await(), posts = posts.await())
    }

核心原則

1. 空值安全

Kotlin 的型別系統區分可空與不可空型別。請充分利用它。

// 好:預設使用不可空型別
fun getUser(id: String): User {
    return userRepository.findById(id)
        ?: throw UserNotFoundException("找不到使用者 $id")
}

// 好:安全呼叫與 Elvis 運算子
fun getUserEmail(userId: String): String {
    val user = userRepository.findById(userId)
    return user?.email ?: "unknown@example.com"
}

// 壞:強制解開可空型別
fun getUserEmail(userId: String): String {
    val user = userRepository.findById(userId)
    return user!!.email // 若為 null 則拋出 NPE
}

2. 預設不可變性

偏好 val 勝過 var,不可變集合勝過可變集合。

// 好:不可變資料
data class User(
    val id: String,
    val name: String,
    val email: String,
)

// 好:使用 copy() 轉換
fun updateEmail(user: User, newEmail: String): User =
    user.copy(email = newEmail)

// 好:不可變集合
val users: List<User> = listOf(user1, user2)
val filtered = users.filter { it.email.isNotBlank() }

// 壞:可變狀態
var currentUser: User? = null // 避免可變的全域狀態
val mutableUsers = mutableListOf<User>() // 除非真的需要,否則避免

3. 表達式主體與單一表達式函式

使用表達式主體來撰寫簡潔、易讀的函式。

// 好:表達式主體
fun isAdult(age: Int): Boolean = age >= 18

fun formatFullName(first: String, last: String): String =
    "$first $last".trim()

fun User.displayName(): String =
    name.ifBlank { email.substringBefore('@') }

// 好:when 作為表達式
fun statusMessage(code: Int): String = when (code) {
    200 -> "OK"
    404 -> "Not Found"
    500 -> "Internal Server Error"
    else -> "未知狀態:$code"
}

// 壞:不必要的區塊主體
fun isAdult(age: Int): Boolean {
    return age >= 18
}

4. 用於值物件的資料類別

對主要用於儲存資料的型別使用資料類別。

// 好:具有 copy、equals、hashCode、toString 的資料類別
data class CreateUserRequest(
    val name: String,
    val email: String,
    val role: Role = Role.USER,
)

// 好:用於型別安全的值類別(執行時期零開銷)
@JvmInline
value class UserId(val value: String) {
    init {
        require(value.isNotBlank()) { "UserId 不能為空白" }
    }
}

@JvmInline
value class Email(val value: String) {
    init {
        require('@' in value) { "無效的 Email:$value" }
    }
}

fun getUser(id: UserId): User = userRepository.findById(id)

密封類別與介面

建模受限的階層

// 好:用於窮舉 when 的密封類別
sealed class Result<out T> {
    data class Success<T>(val data: T) : Result<T>()
    data class Failure(val error: AppError) : Result<Nothing>()
    data object Loading : Result<Nothing>()
}

fun <T> Result<T>.getOrNull(): T? = when (this) {
    is Result.Success -> data
    is Result.Failure -> null
    is Result.Loading -> null
}

fun <T> Result<T>.getOrThrow(): T = when (this) {
    is Result.Success -> data
    is Result.Failure -> throw error.toException()
    is Result.Loading -> throw IllegalStateException("仍在載入中")
}

用於 API 回應的密封介面

sealed interface ApiError {
    val message: String

    data class NotFound(override val message: String) : ApiError
    data class Unauthorized(override val message: String) : ApiError
    data class Validation(
        override val message: String,
        val field: String,
    ) : ApiError
    data class Internal(
        override val message: String,
        val cause: Throwable? = null,
    ) : ApiError
}

fun ApiError.toStatusCode(): Int = when (this) {
    is ApiError.NotFound -> 404
    is ApiError.Unauthorized -> 401
    is ApiError.Validation -> 422
    is ApiError.Internal -> 500
}

作用域函式

何時使用哪一個

// let:轉換可空或作用域結果
val length: Int? = name?.let { it.trim().length }

// apply:設定物件(回傳物件本身)
val user = User().apply {
    name = "Alice"
    email = "alice@example.com"
}

// also:副作用(回傳物件本身)
val user = createUser(request).also { logger.info("已建立使用者:${it.id}") }

// run:以接收者執行區塊(回傳結果)
val result = connection.run {
    prepareStatement(sql)
    executeQuery()
}

// with:run 的非擴充形式
val csv = with(StringBuilder()) {
    appendLine("name,email")
    users.forEach { appendLine("${it.name},${it.email}") }
    toString()
}

反模式

// 壞:巢狀作用域函式
user?.let { u ->
    u.address?.let { addr ->
        addr.city?.let { city ->
            println(city) // 難以閱讀
        }
    }
}

// 好:改用鏈式安全呼叫
val city = user?.address?.city
city?.let { println(it) }

擴充函式

在不使用繼承的情況下新增功能

// 好:領域特定的擴充
fun String.toSlug(): String =
    lowercase()
        .replace(Regex("[^a-z0-9\\s-]"), "")
        .replace(Regex("\\s+"), "-")
        .trim('-')

fun Instant.toLocalDate(zone: ZoneId = ZoneId.systemDefault()): LocalDate =
    atZone(zone).toLocalDate()

// 好:集合擴充
fun <T> List<T>.second(): T = this[1]

fun <T> List<T>.secondOrNull(): T? = getOrNull(1)

// 好:作用域擴充(不污染全域命名空間)
class UserService {
    private fun User.isActive(): Boolean =
        status == Status.ACTIVE && lastLogin.isAfter(Instant.now().minus(30, ChronoUnit.DAYS))

    fun getActiveUsers(): List<User> = userRepository.findAll().filter { it.isActive() }
}

協程

結構化並行

// 好:使用 coroutineScope 的結構化並行
suspend fun fetchUserWithPosts(userId: String): UserProfile =
    coroutineScope {
        val userDeferred = async { userService.getUser(userId) }
        val postsDeferred = async { postService.getUserPosts(userId) }

        UserProfile(
            user = userDeferred.await(),
            posts = postsDeferred.await(),
        )
    }

// 好:當子協程可獨立失敗時使用 supervisorScope
suspend fun fetchDashboard(userId: String): Dashboard =
    supervisorScope {
        val user = async { userService.getUser(userId) }
        val notifications = async { notificationService.getRecent(userId) }
        val recommendations = async { recommendationService.getFor(userId) }

        Dashboard(
            user = user.await(),
            notifications = try {
                notifications.await()
            } catch (e: CancellationException) {
                throw e
            } catch (e: Exception) {
                emptyList()
            },
            recommendations = try {
                recommendations.await()
            } catch (e: CancellationException) {
                throw e
            } catch (e: Exception) {
                emptyList()
            },
        )
    }

用於反應式串流的 Flow

// 好:具有適當錯誤處理的冷流
fun observeUsers(): Flow<List<User>> = flow {
    while (currentCoroutineContext().isActive) {
        val users = userRepository.findAll()
        emit(users)
        delay(5.seconds)
    }
}.catch { e ->
    logger.error("觀察使用者時發生錯誤", e)
    emit(emptyList())
}

// 好:Flow 運算子
fun searchUsers(query: Flow<String>): Flow<List<User>> =
    query
        .debounce(300.milliseconds)
        .distinctUntilChanged()
        .filter { it.length >= 2 }
        .mapLatest { q -> userRepository.search(q) }
        .catch { emit(emptyList()) }

取消與清理

// 好:尊重取消
suspend fun processItems(items: List<Item>) {
    items.forEach { item ->
        ensureActive() // 在昂貴操作前檢查取消
        processItem(item)
    }
}

// 好:使用 try/finally 清理
suspend fun acquireAndProcess() {
    val resource = acquireResource()
    try {
        resource.process()
    } finally {
        withContext(NonCancellable) {
            resource.release() // 即使取消也總是釋放
        }
    }
}

委派

屬性委派

// 惰性初始化
val expensiveData: List<User> by lazy {
    userRepository.findAll()
}

// 可觀察屬性
var name: String by Delegates.observable("initial") { _, old, new ->
    logger.info("名稱從 '$old' 變更為 '$new'")
}

// 基於 Map 的屬性
class Config(private val map: Map<String, Any?>) {
    val host: String by map
    val port: Int by map
    val debug: Boolean by map
}

val config = Config(mapOf("host" to "localhost", "port" to 8080, "debug" to true))

介面委派

// 好:委派介面實作
class LoggingUserRepository(
    private val delegate: UserRepository,
    private val logger: Logger,
) : UserRepository by delegate {
    // 僅覆寫需要新增日誌的部分
    override suspend fun findById(id: String): User? {
        logger.info("依 ID 尋找使用者:$id")
        return delegate.findById(id).also {
            logger.info("找到使用者:${it?.name ?: "null"}")
        }
    }
}

DSL 建構器

型別安全建構器

// 好:使用 @DslMarker 的 DSL
@DslMarker
annotation class HtmlDsl

@HtmlDsl
class HTML {
    private val children = mutableListOf<Element>()

    fun head(init: Head.() -> Unit) {
        children += Head().apply(init)
    }

    fun body(init: Body.() -> Unit) {
        children += Body().apply(init)
    }

    override fun toString(): String = children.joinToString("\n")
}

fun html(init: HTML.() -> Unit): HTML = HTML().apply(init)

// 使用方式
val page = html {
    head { title("我的頁面") }
    body {
        h1("歡迎")
        p("Hello, World!")
    }
}

配置 DSL

data class ServerConfig(
    val host: String = "0.0.0.0",
    val port: Int = 8080,
    val ssl: SslConfig? = null,
    val database: DatabaseConfig? = null,
)

data class SslConfig(val certPath: String, val keyPath: String)
data class DatabaseConfig(val url: String, val maxPoolSize: Int = 10)

class ServerConfigBuilder {
    var host: String = "0.0.0.0"
    var port: Int = 8080
    private var ssl: SslConfig? = null
    private var database: DatabaseConfig? = null

    fun ssl(certPath: String, keyPath: String) {
        ssl = SslConfig(certPath, keyPath)
    }

    fun database(url: String, maxPoolSize: Int = 10) {
        database = DatabaseConfig(url, maxPoolSize)
    }

    fun build(): ServerConfig = ServerConfig(host, port, ssl, database)
}

fun serverConfig(init: ServerConfigBuilder.() -> Unit): ServerConfig =
    ServerConfigBuilder().apply(init).build()

// 使用方式
val config = serverConfig {
    host = "0.0.0.0"
    port = 443
    ssl("/certs/cert.pem", "/certs/key.pem")
    database("jdbc:postgresql://localhost:5432/mydb", maxPoolSize = 20)
}

用於惰性求值的 Sequence

// 好:對大型集合進行多個操作時使用 sequence
val result = users.asSequence()
    .filter { it.isActive }
    .map { it.email }
    .filter { it.endsWith("@company.com") }
    .take(10)
    .toList()

// 好:產生無限序列
val fibonacci: Sequence<Long> = sequence {
    var a = 0L
    var b = 1L
    while (true) {
        yield(a)
        val next = a + b
        a = b
        b = next
    }
}

val first20 = fibonacci.take(20).toList()

Gradle Kotlin DSL

build.gradle.kts 配置

// 檢查最新版本:https://kotlinlang.org/docs/releases.html
plugins {
    kotlin("jvm") version "2.3.10"
    kotlin("plugin.serialization") version "2.3.10"
    id("io.ktor.plugin") version "3.4.0"
    id("org.jetbrains.kotlinx.kover") version "0.9.7"
    id("io.gitlab.arturbosch.detekt") version "1.23.8"
}

group = "com.example"
version = "1.0.0"

kotlin {
    jvmToolchain(21)
}

dependencies {
    // Ktor
    implementation("io.ktor:ktor-server-core:3.4.0")
    implementation("io.ktor:ktor-server-netty:3.4.0")
    implementation("io.ktor:ktor-server-content-negotiation:3.4.0")
    implementation("io.ktor:ktor-serialization-kotlinx-json:3.4.0")

    // Exposed
    implementation("org.jetbrains.exposed:exposed-core:1.0.0")
    implementation("org.jetbrains.exposed:exposed-dao:1.0.0")
    implementation("org.jetbrains.exposed:exposed-jdbc:1.0.0")
    implementation("org.jetbrains.exposed:exposed-kotlin-datetime:1.0.0")

    // Koin
    implementation("io.insert-koin:koin-ktor:4.2.0")

    // Coroutines
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")

    // Testing
    testImplementation("io.kotest:kotest-runner-junit5:6.1.4")
    testImplementation("io.kotest:kotest-assertions-core:6.1.4")
    testImplementation("io.kotest:kotest-property:6.1.4")
    testImplementation("io.mockk:mockk:1.14.9")
    testImplementation("io.ktor:ktor-server-test-host:3.4.0")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
}

tasks.withType<Test> {
    useJUnitPlatform()
}

detekt {
    config.setFrom(files("config/detekt/detekt.yml"))
    buildUponDefaultConfig = true
}

錯誤處理模式

用於領域操作的 Result 型別

// 好:使用 Kotlin 的 Result 或自訂密封類別
suspend fun createUser(request: CreateUserRequest): Result<User> = runCatching {
    require(request.name.isNotBlank()) { "名稱不能為空白" }
    require('@' in request.email) { "無效的 Email 格式" }

    val user = User(
        id = UserId(UUID.randomUUID().toString()),
        name = request.name,
        email = Email(request.email),
    )
    userRepository.save(user)
    user
}

// 好:鏈式結果
val displayName = createUser(request)
    .map { it.name }
    .getOrElse { "Unknown" }

require、check、error

// 好:具有明確訊息的先決條件
fun withdraw(account: Account, amount: Money): Account {
    require(amount.value > 0) { "金額必須為正數:$amount" }
    check(account.balance >= amount) { "餘額不足:${account.balance} < $amount" }

    return account.copy(balance = account.balance - amount)
}

集合操作

慣用的集合處理

// 好:鏈式操作
val activeAdminEmails: List<String> = users
    .filter { it.role == Role.ADMIN && it.isActive }
    .sortedBy { it.name }
    .map { it.email }

// 好:分組與聚合
val usersByRole: Map<Role, List<User>> = users.groupBy { it.role }

val oldestByRole: Map<Role, User?> = users.groupBy { it.role }
    .mapValues { (_, users) -> users.minByOrNull { it.createdAt } }

// 好:使用 associateBy 建立 Map
val usersById: Map<UserId, User> = users.associateBy { it.id }

// 好:使用 partition 分割
val (active, inactive) = users.partition { it.isActive }

快速參考:Kotlin 慣用語

慣用語 說明
val 勝過 var 偏好不可變變數
data class 用於具有 equals/hashCode/copy 的值物件
sealed class/interface 用於受限的型別階層
value class 用於零開銷的型別安全包裝器
表達式 when 窮舉模式匹配
安全呼叫 ?. 空安全的成員存取
Elvis ?: 可空型別的預設值
let/apply/also/run/with 用於簡潔程式碼的作用域函式
擴充函式 在不使用繼承的情況下新增行為
copy() 資料類別的不可變更新
require/check 先決條件斷言
協程 async/await 結構化並行執行
Flow 冷反應式串流
sequence 惰性求值
委派 by 在不使用繼承的情況下重複使用實作

應避免的反模式

// 壞:強制解開可空型別
val name = user!!.name

// 壞:來自 Java 的平台型別洩漏
fun getLength(s: String) = s.length // 安全
fun getLength(s: String?) = s?.length ?: 0 // 處理來自 Java 的 null

// 壞:可變資料類別
data class MutableUser(var name: String, var email: String)

// 壞:使用例外進行控制流程
try {
    val user = findUser(id)
} catch (e: NotFoundException) {
    // 不要對預期情況使用例外
}

// 好:使用可空回傳值或 Result
val user: User? = findUserOrNull(id)

// 壞:忽略協程作用域
GlobalScope.launch { /* 避免 GlobalScope */ }

// 好:使用結構化並行
coroutineScope {
    launch { /* 適當的作用域 */ }
}

// 壞:深度巢狀的作用域函式
user?.let { u ->
    u.address?.let { a ->
        a.city?.let { c -> process(c) }
    }
}

// 好:直接的空安全鏈
user?.address?.city?.let { process(it) }

請記住:Kotlin 程式碼應簡潔但可讀。利用型別系統確保安全,偏好不可變性,並使用協程處理並行。如有疑問,讓編譯器協助您。