moai-lang-kotlin
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseQuick Reference (30 seconds)
快速参考(30秒)
Kotlin 2.0+ Expert - K2 compiler, coroutines, Ktor, Compose Multiplatform with Context7 integration.
Auto-Triggers: Kotlin files (, ), Gradle Kotlin DSL (, )
.kt.ktsbuild.gradle.ktssettings.gradle.ktsCore Capabilities:
- Kotlin 2.0: K2 compiler, coroutines, Flow, sealed classes, value classes
- Ktor 3.0: Async HTTP server/client, WebSocket, JWT authentication
- Exposed 0.55: Kotlin SQL framework with coroutines support
- Spring Boot (Kotlin): Kotlin-idiomatic Spring with WebFlux
- Compose Multiplatform: Desktop, iOS, Web, Android UI
- Testing: JUnit 5, MockK, Kotest, Turbine for Flow testing
Kotlin 2.0+专家 - 涵盖K2编译器、coroutines、Ktor、集成Context7的Compose Multiplatform。
自动触发场景:Kotlin文件(、)、Gradle Kotlin DSL(、)
.kt.ktsbuild.gradle.ktssettings.gradle.kts核心能力:
- Kotlin 2.0:K2编译器、coroutines、Flow、sealed classes、value classes
- Ktor 3.0:异步HTTP服务器/客户端、WebSocket、JWT身份验证
- Exposed 0.55:支持coroutines的Kotlin SQL框架
- Spring Boot(Kotlin):符合Kotlin惯用风格的Spring WebFlux
- Compose Multiplatform:桌面端、iOS、Web、Android UI
- 测试:JUnit 5、MockK、Kotest、用于Flow测试的Turbine
Implementation Guide (5 minutes)
实施指南(5分钟)
Kotlin 2.0 Features
Kotlin 2.0特性
Coroutines and Flow: Use coroutineScope with async for parallel operations. Create deferred values with async, then call await on each to get results. Combine results into data classes. For reactive streams, create flow blocks with emit calls inside while loops. Use delay for intervals and flowOn to specify dispatcher.
Sealed Classes and Value Classes: Define sealed interface with generic type parameter. Create data class implementations for success and data object for stateless cases like Loading. Use @JvmInline annotation with value class wrapping a primitive. Add init blocks with require for validation.
Coroutines与Flow:使用coroutineScope结合async实现并行操作。通过async创建延迟值,然后调用每个值的await方法获取结果。将结果组合为数据类。对于响应式流,在while循环内通过emit调用创建flow块。使用delay设置间隔,使用flowOn指定调度器。
Sealed Classes与Value Classes:定义带泛型类型参数的sealed接口。为成功状态创建数据类实现,为加载等无状态场景创建数据对象。使用@JvmInline注解,让value类包装基本类型。添加包含require的init块进行验证。
Ktor 3.0 Server
Ktor 3.0服务器
Application Setup: Call embeddedServer with Netty, port, and host parameters. Inside the lambda, call configuration functions for Koin, security, routing, and content negotiation. Call start with wait equals true.
For Koin configuration, install Koin plugin and define modules with single declarations for singletons. For security, install Authentication plugin and configure JWT with realm, verifier, and validate callback. For content negotiation, install ContentNegotiation with json configuration.
Routing with Authentication: Define routing function on Application. Inside routing block, use route for path prefixes. Create unauthenticated endpoints with post and call.receive for request body. Use authenticate block with verifier name for protected routes. Inside route blocks, define get endpoints with call.parameters for path/query params. Use call.respond with status code and response body.
应用设置:调用带有Netty、端口和主机参数的embeddedServer。在lambda表达式中,调用Koin、安全、路由和内容协商的配置函数。调用start方法并设置wait为true。
Koin配置:安装Koin插件,通过single声明定义单例模块。安全配置:安装Authentication插件,使用realm、verifier和validate回调配置JWT。内容协商:安装带有json配置的ContentNegotiation。
带身份验证的路由:在Application上定义routing函数。在routing块内,使用route设置路径前缀。通过post创建未认证端点,使用call.receive获取请求体。使用带有验证器名称的authenticate块保护路由。在route块内,通过call.parameters定义带路径/查询参数的get端点。使用call.respond返回状态码和响应体。
Exposed SQL Framework
Exposed SQL框架
Table and Entity: Define object extending LongIdTable with table name. Declare columns with varchar, enumerationByName, and timestamp functions. Use uniqueIndex() and defaultExpression for defaults.
Create entity class extending LongEntity with companion object extending LongEntityClass. Declare properties with by syntax using table column references. Create toModel function to map entity to domain model.
Repository with Coroutines: Create repository implementation taking Database parameter. Implement suspend functions wrapping Exposed operations in dbQuery helper. Use findById for single entity lookup. Use Entity.new for inserts. Define private dbQuery function using newSuspendedTransaction with IO dispatcher.
表与实体:定义继承LongIdTable的对象并指定表名。使用varchar、enumerationByName和timestamp函数声明列。使用uniqueIndex()和defaultExpression设置默认值。
创建继承LongEntity的实体类,其伴生对象继承LongEntityClass。使用by语法结合表列引用声明属性。创建toModel函数将实体映射为领域模型。
带Coroutines的仓库:创建接收Database参数的仓库实现。将Exposed操作包装在dbQuery辅助函数中,实现挂起函数。使用findById查找单个实体。使用Entity.new执行插入操作。使用IO调度器的newSuspendedTransaction定义私有dbQuery函数。
Spring Boot with Kotlin
基于Kotlin的Spring Boot
WebFlux Controller: Annotate class with @RestController and @RequestMapping. Create suspend functions for endpoints with @GetMapping and @PostMapping. Return Flow for collections using map to convert entities. Return ResponseEntity with status codes. Use @Valid for request validation.
WebFlux控制器:使用@RestController和@RequestMapping注解类。为端点创建带@GetMapping和@PostMapping的挂起函数。返回Flow类型的集合,通过map转换实体。返回带状态码的ResponseEntity。使用@Valid进行请求验证。
Advanced Patterns
高级模式
Compose Multiplatform
Compose Multiplatform
Shared UI Component: Create @Composable function taking ViewModel and callback parameters. Collect uiState as state with collectAsState. Use when expression on sealed state to show different composables for Loading, Success, and Error.
For list items, create Card composables with Modifier.fillMaxWidth and clickable. Use Row with padding, AsyncImage for avatars with CircleShape clip, and Column for text content with MaterialTheme.typography.
共享UI组件:创建接收ViewModel和回调参数的@Composable函数。使用collectAsState将uiState收集为状态。对密封状态使用when表达式,为加载、成功和错误状态显示不同的可组合项。
对于列表项,创建带有Modifier.fillMaxWidth和clickable的Card可组合项。使用带内边距的Row、带CircleShape裁剪的AsyncImage(用于头像),以及带MaterialTheme.typography的Column(用于文本内容)。
Testing with MockK
使用MockK进行测试
Create test class with mockk for dependencies. Initialize service with mock in declaration. Use @Test with runTest for coroutine tests. Use coEvery with coAnswers for async mocking with delay. Use assertThat for assertions. For Flow testing, use toList to collect emissions and assert on size and content.
创建使用mockk模拟依赖的测试类。在声明中使用模拟对象初始化服务。在协程测试中结合@Test使用runTest。使用coEvery和coAnswers实现带延迟的异步模拟。使用assertThat进行断言。对于Flow测试,使用toList收集发射项并断言其大小和内容。
Gradle Build Configuration
Gradle构建配置
Use plugins block with kotlin("jvm") and kotlin("plugin.serialization") with version strings. Add id for ktor.plugin. Configure kotlin block with jvmToolchain. In dependencies block, add ktor server modules, kotlinx coroutines, exposed modules, and postgresql driver. Add test dependencies for mockk, coroutines-test, and turbine.
使用plugins块,添加带版本号的kotlin("jvm")和kotlin("plugin.serialization")。添加ktor.plugin的id。配置kotlin块的jvmToolchain。在dependencies块中,添加ktor服务器模块、kotlinx coroutines、exposed模块和postgresql驱动。添加mockk、coroutines-test和turbine作为测试依赖。
Context7 Integration
Context7集成
Library mappings for latest documentation:
- - Ktor 3.0 server/client documentation
/ktorio/ktor - - Exposed SQL framework
/jetbrains/exposed - - Kotlin 2.0 language reference
/JetBrains/kotlin - - Coroutines library
/Kotlin/kotlinx.coroutines - - Compose Multiplatform
/jetbrains/compose-multiplatform - - Arrow functional programming
/arrow-kt/arrow
Usage: Call mcp__context7__get_library_docs with context7CompatibleLibraryID, topic string for specific areas, and tokens parameter for response size.
最新文档的库映射:
- - Ktor 3.0服务器/客户端文档
/ktorio/ktor - - Exposed SQL框架文档
/jetbrains/exposed - - Kotlin 2.0语言参考文档
/JetBrains/kotlin - - Coroutines库文档
/Kotlin/kotlinx.coroutines - - Compose Multiplatform文档
/jetbrains/compose-multiplatform - - Arrow函数式编程文档
/arrow-kt/arrow
使用方法:调用mcp__context7__get_library_docs,传入context7CompatibleLibraryID、特定领域的主题字符串和用于设置响应大小的tokens参数。
When to Use Kotlin
Kotlin适用场景
Use Kotlin When:
- Developing Android applications (official language)
- Building modern server applications with Ktor
- Preferring concise, expressive syntax
- Building reactive services with coroutines and Flow
- Creating multiplatform applications (iOS, Desktop, Web)
- Full Java interoperability required
Consider Alternatives When:
- Legacy Java codebase requiring minimal changes
- Big data pipelines (prefer Scala with Spark)
以下场景适用Kotlin:
- 开发Android应用(官方语言)
- 使用Ktor构建现代服务器应用
- 偏好简洁、富有表现力的语法
- 使用coroutines和Flow构建响应式服务
- 创建多平台应用(iOS、桌面端、Web)
- 需要完全的Java互操作性
以下场景考虑替代方案:
- 遗留Java代码库,需要最小化修改
- 大数据管道(优先选择Scala+Spark)
Works Well With
兼容工具
- - Java interoperability and Spring Boot patterns
moai-lang-java - - REST API, GraphQL, microservices architecture
moai-domain-backend - - JPA, Exposed, R2DBC patterns
moai-domain-database - - JUnit 5, MockK, TestContainers integration
moai-quality-testing - - JVM container optimization
moai-infra-docker
- - Java互操作性及Spring Boot模式
moai-lang-java - - REST API、GraphQL、微服务架构
moai-domain-backend - - JPA、Exposed、R2DBC模式
moai-domain-database - - JUnit 5、MockK、TestContainers集成
moai-quality-testing - - JVM容器优化
moai-infra-docker
Troubleshooting
故障排除
K2 Compiler: Add kotlin.experimental.tryK2=true to gradle.properties. Clear .gradle directory for full rebuild.
Coroutines: Avoid runBlocking in suspend contexts. Use Dispatchers.IO for blocking operations.
Ktor: Ensure ContentNegotiation is installed. Check JWT verifier configuration. Verify routing hierarchy.
Exposed: Ensure all DB operations run within transaction context. Be aware of lazy entity loading outside transactions.
K2编译器:在gradle.properties中添加kotlin.experimental.tryK2=true。清理.gradle目录以完全重建。
Coroutines:避免在挂起上下文中使用runBlocking。使用Dispatchers.IO处理阻塞操作。
Ktor:确保已安装ContentNegotiation。检查JWT验证器配置。验证路由层级。
Exposed:确保所有数据库操作在事务上下文中运行。注意事务外的延迟实体加载问题。
Advanced Documentation
高级文档
For comprehensive reference materials:
- reference.md - Complete ecosystem, Context7 mappings, testing patterns, performance
- examples.md - Production-ready code examples, Ktor, Compose, Android patterns
Last Updated: 2026-01-11
Status: Production Ready (v1.1.0)
如需完整参考资料:
- reference.md - 完整生态系统、Context7映射、测试模式、性能优化
- examples.md - 生产就绪代码示例、Ktor、Compose、Android模式
最后更新:2026-01-11
状态:生产就绪(v1.1.0)