kotlin

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kotlin

Kotlin

Modern Kotlin development with coroutines, null safety, and idiomatic patterns.
基于协程、空安全和惯用模式的现代Kotlin开发。

When to Use

适用场景

  • Working with
    .kt
    files
  • Android app development
  • JVM backend with Spring Boot/Ktor
  • Multiplatform projects (KMP)
  • 处理.kt文件
  • Android应用开发
  • 使用Spring Boot/Ktor的JVM后端开发
  • 多平台项目(KMP)

Quick Start

快速开始

kotlin
data class User(
    val id: String,
    val name: String,
    val email: String,
    val createdAt: Instant = Clock.System.now()
)

suspend fun fetchUser(id: String): User? {
    return apiService.getUser(id)
}
kotlin
data class User(
    val id: String,
    val name: String,
    val email: String,
    val createdAt: Instant = Clock.System.now()
)

suspend fun fetchUser(id: String): User? {
    return apiService.getUser(id)
}

Core Concepts

核心概念

Null Safety

空安全

kotlin
// Nullable types
val name: String? = null

// Safe calls
val length = name?.length

// Elvis operator
val len = name?.length ?: 0

// Smart casts
if (name != null) {
    println(name.length) // Smart cast to String
}

// Not-null assertion (use sparingly)
val len = name!!.length
kotlin
// 可空类型
val name: String? = null

// 安全调用
val length = name?.length

// Elvis操作符
val len = name?.length ?: 0

// 智能类型转换
if (name != null) {
    println(name.length) // 智能转换为String
}

// 非空断言(谨慎使用)
val len = name!!.length

Data Classes & Sealed Classes

数据类与密封类

kotlin
data class User(
    val id: String,
    val name: String,
    val email: String
)

sealed class Result<out T> {
    data class Success<T>(val data: T) : Result<T>()
    data class Error(val message: String) : Result<Nothing>()
    object Loading : Result<Nothing>()
}

// Exhaustive when
fun handleResult(result: Result<User>) = when (result) {
    is Result.Success -> println(result.data)
    is Result.Error -> println(result.message)
    Result.Loading -> println("Loading...")
}
kotlin
data class User(
    val id: String,
    val name: String,
    val email: String
)

sealed class Result<out T> {
    data class Success<T>(val data: T) : Result<T>()
    data class Error(val message: String) : Result<Nothing>()
    object Loading : Result<Nothing>()
}

// 穷尽式when表达式
fun handleResult(result: Result<User>) = when (result) {
    is Result.Success -> println(result.data)
    is Result.Error -> println(result.message)
    Result.Loading -> println("Loading...")
}

Common Patterns

常见模式

Coroutines

协程

kotlin
// Suspend function
suspend fun fetchData(): List<Item> {
    return withContext(Dispatchers.IO) {
        api.fetchItems()
    }
}

// Parallel execution
suspend fun loadDashboard(): Dashboard {
    return coroutineScope {
        val user = async { fetchUser() }
        val orders = async { fetchOrders() }
        Dashboard(user.await(), orders.await())
    }
}

// Flow for streams
fun observeUsers(): Flow<List<User>> = flow {
    while (true) {
        emit(fetchUsers())
        delay(5000)
    }
}.flowOn(Dispatchers.IO)
kotlin
// 挂起函数
suspend fun fetchData(): List<Item> {
    return withContext(Dispatchers.IO) {
        api.fetchItems()
    }
}

// 并行执行
suspend fun loadDashboard(): Dashboard {
    return coroutineScope {
        val user = async { fetchUser() }
        val orders = async { fetchOrders() }
        Dashboard(user.await(), orders.await())
    }
}

// 用于流处理的Flow
fun observeUsers(): Flow<List<User>> = flow {
    while (true) {
        emit(fetchUsers())
        delay(5000)
    }
}.flowOn(Dispatchers.IO)

Extension Functions

扩展函数

kotlin
fun String.isValidEmail(): Boolean {
    return Regex("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}\$").matches(this)
}

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

inline fun <T> Result<T>.onSuccess(action: (T) -> Unit): Result<T> {
    if (this is Result.Success) action(data)
    return this
}
kotlin
fun String.isValidEmail(): Boolean {
    return Regex("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}\$").matches(this)
}

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

inline fun <T> Result<T>.onSuccess(action: (T) -> Unit): Result<T> {
    if (this is Result.Success) action(data)
    return this
}

Best Practices

最佳实践

Do:
  • Use data classes for DTOs
  • Prefer immutability (
    val
    over
    var
    )
  • Use sealed classes for state
  • Use coroutines for async work
Don't:
  • Use
    !!
    without null check
  • Create utility classes (use extensions)
  • Block main thread with
    runBlocking
  • Ignore cancellation in coroutines
建议:
  • 使用数据类实现DTO
  • 优先使用不可变类型(用
    val
    而非
    var
  • 使用密封类管理状态
  • 使用协程处理异步任务
不建议:
  • 不要在未做空检查时使用
    !!
  • 不要创建工具类(使用扩展函数)
  • 不要用
    runBlocking
    阻塞主线程
  • 不要忽略协程的取消操作

Troubleshooting

故障排除

ErrorCauseSolution
NullPointerException
Force unwrap on nullUse safe call
?.
CancellationException
Coroutine cancelledHandle or propagate
IllegalStateException
Invalid state accessCheck state before access
错误类型原因解决方案
NullPointerException
对空值进行强制解包使用安全调用
?.
CancellationException
协程被取消处理或传播取消信号
IllegalStateException
访问无效状态访问前检查状态

References

参考资料