kotlin-rules

Kotlin 规则:关于 Kotlin 的编码规范,涵盖风格、设计模式、安全性与测试。触发条件包括 .kt、.kts、build.gradle.kts 文件或 Ktor、Jetpack Compose、协程、kotlinx 相关项目。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "kotlin-rules":https://skillpi.com/zh/skills/deepskill-057e4927bc443d6566d824e07e70d812385b870d4ddc902cdcb950ad9be3f419。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Kotlin 规则:关于 Kotlin 的编码规范,涵盖风格、设计模式、安全性与测试。触发条件包括 .kt、.kts、build.gradle.kts 文件或 Ktor、Jetpack Compose、协程、kotlinx 相关项目。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: kotlin-rules
description: "Kotlin coding rules: style, patterns, security, testing. Triggers: .kt, .kts, build.gradle.kts, Ktor, Jetpack Compose, coroutines, kotlinx."
effort: medium
user-invocable: false
allowed-tools: Read

Kotlin Rules

These rules come from app/rules/kotlin/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Kotlin. Apply them when writing or reviewing Kotlin code.

Kotlin Coding Style

Naming

  • PascalCase: classes, interfaces, objects, type aliases, enum entries.
  • camelCase: functions, properties, local variables, parameters.
  • UPPER_SNAKE: compile-time constants (const val), top-level val constants.
  • Backing properties: prefix with _ (private val _items, val items: List<T>).
  • Package names: lowercase, no underscores (com.company.project.feature).

Null Safety

  • Use nullable types only when nullability is semantically meaningful.
  • Prefer ?.let { }, ?: (Elvis), and safe calls over !!.
  • Never use !! except in tests or when null is truly impossible.
  • Use requireNotNull() and require() for preconditions at public API boundaries.
  • Use checkNotNull() and check() for state assertions.

Data Classes

  • Use data class for DTOs, value objects, and state containers.
  • Use copy() for immutable updates. Avoid mutable var in data classes.
  • Use sealed class / sealed interface for restricted hierarchies.
  • Use value class (inline class) for type-safe wrappers with zero overhead.
  • Use object for singletons and namespace-like utility groupings.

Functions

  • Use expression body (= expr) for single-expression functions.
  • Use named arguments for functions with >2 parameters of the same type.
  • Use default parameter values instead of overloaded functions.
  • Use extension functions to add behavior without inheritance.
  • Use suspend functions for async operations, not callbacks.

Collections

  • Prefer listOf, mapOf, setOf (immutable) over mutableListOf.
  • Use collection operators: map, filter, groupBy, associate.
  • Use sequence {} for lazy evaluation on large collections.
  • Prefer firstOrNull() over first() for safe access.
  • Use destructuring: val (name, age) = user.

Scope Functions

  • let: null-safe chaining and local scoping.
  • apply: configure object after creation.
  • also: side effects (logging, validation) in chains.
  • run: compute a result using receiver's context.
  • with: multiple operations on an object without chaining.
  • Avoid nesting scope functions more than 1 level deep.

Formatting

  • Use ktlint or detekt for automated formatting and linting.
  • Use trailing commas in multi-line parameter/argument lists.
  • Max line length: 120 characters (Kotlin convention).
  • Use when expression over if-else chains for 3+ branches.

Kotlin Frameworks

Ktor (Server)

  • Use routing DSL: routing { get("/users") { call.respond(users) } }.
  • Use install() for plugins: ContentNegotiation, Authentication, CORS.
  • Use call.receive<T>() for typed request body parsing with kotlinx.serialization.
  • Use StatusPages plugin for centralized error handling.
  • Use Routing with nested route("/api/v1") { } blocks for URL grouping.

Ktor (Client)

  • Use HttpClient with engine configuration (CIO, OkHttp, Apache).
  • Use install(ContentNegotiation) { json() } for JSON serialization.
  • Use client.get<T>() with reified type for typed responses.
  • Use HttpTimeout plugin for connection and request timeouts.
  • Close HttpClient when done or use DI lifecycle management.

Spring Boot (Kotlin)

  • Use constructor injection (Kotlin classes are final by default).
  • Apply kotlin-spring plugin for open classes (required for proxying).
  • Use @ConfigurationProperties with data classes for typed config.
  • Use WebFlux with coroutines: coRouter { } and suspend handler functions.
  • Use spring-boot-starter-validation with @Valid on Kotlin data classes.

Exposed (ORM)

  • Use DSL API for type-safe queries: Users.select { Users.name eq "Ada" }.
  • Use DAO API for Active Record-style: User.find { Users.age greaterEq 18 }.
  • Wrap database operations in transaction { } blocks.
  • Use SchemaUtils.create(Users) for schema management in development.

kotlinx.serialization

  • Use @Serializable annotation on data classes for compile-time serialization.
  • Use @SerialName("field_name") for JSON field name mapping.
  • Use Json { ignoreUnknownKeys = true } for lenient deserialization.
  • Use polymorphic serialization with sealed class and @Polymorphic.
  • Prefer kotlinx.serialization over Jackson for pure Kotlin projects.

Koin (DI)

  • Define modules: module { single { UserService(get()) } }.
  • Use by inject<T>() for lazy injection in Android/Ktor.
  • Use factory { } for new instance per injection, single { } for singleton.
  • Use checkModules() in tests to verify DI graph completeness.

Compose (Multiplatform UI)

  • Use @Composable functions for UI components. Keep them stateless.
  • Use remember { } and mutableStateOf() for local state.
  • Hoist state to callers: pass state down, events up.
  • Use LaunchedEffect for side effects tied to composition lifecycle.
  • Use ViewModel with StateFlow for screen-level state management.

Kotlin Patterns

Error Handling

  • Use Result<T> for operations that can fail without exceptions.
  • Use runCatching { } to wrap exception-throwing code into Result.
  • Use sealed class hierarchies for domain errors: sealed class AppError.
  • Prefer fold(), getOrElse(), getOrNull() over getOrThrow().
  • Use require() / check() for preconditions; they throw IllegalArgumentException / IllegalStateException.

Coroutines

  • Use suspend functions for sequential async operations.
  • Use coroutineScope { } for structured concurrency with parallel work.
  • Use async { } + await() for concurrent independent operations.
  • Use supervisorScope { } when child failures should not cancel siblings.
  • Use withContext(Dispatchers.IO) for blocking I/O in coroutine context.
  • Use flow { } for cold asynchronous streams. Collect in lifecycle-aware scope.

Flow Patterns

  • Use stateIn() and shareIn() to convert cold flows to hot shared state.
  • Use combine() to merge multiple flows into derived state.
  • Use flatMapLatest for search-as-you-type patterns (cancel previous).
  • Use catch { } operator for upstream error handling in flows.
  • Use flowOn(Dispatchers.IO) to shift upstream execution context.

Sealed Hierarchies

  • Use sealed interface over sealed class when no shared state is needed.
  • Use when expressions exhaustively on sealed types (compiler-enforced).
  • Combine sealed types with data classes for typed state machines.
  • Use sealed hierarchies for API responses: Success<T>, Error, Loading.

Delegation

  • Use by lazy { } for thread-safe lazy initialization.
  • Use by map for delegated properties backed by a Map.
  • Use class delegation (class Foo : Bar by impl) to favor composition.
  • Use observable / vetoable delegates for reactive property changes.

Builder Patterns

  • Use DSL-style builders with @DslMarker annotation to prevent scope leakage.
  • Use trailing lambda syntax for configuration blocks.
  • Use apply { } for inline object configuration without a dedicated builder.
  • Use buildList { }, buildMap { }, buildString { } for collection construction.

Anti-Patterns

  • Overusing !!: masks null-safety guarantees. Use safe calls or require.
  • Nesting scope functions: foo.let { it.also { ... }.run { } } -- flatten logic.
  • Blocking the main thread: use withContext(Dispatchers.IO) for I/O.
  • Using GlobalScope.launch: leaks coroutines. Use structured concurrency.
  • Mutable shared state without synchronization: use Mutex or StateFlow.

Kotlin Security

Input Validation

  • Validate all inputs at API boundaries using Bean Validation or manual checks.
  • Use require() for argument validation: require(age > 0) { "Age must be positive" }.
  • Use data class init blocks for domain validation on construction.
  • Never trust client-provided IDs. Verify resource ownership server-side.
  • Sanitize strings before using in HTML, SQL, or shell commands.

Null Safety as Security

  • Kotlin's null safety prevents null pointer exceptions. Do not circumvent with !!.
  • Use ?. and ?: chains for safe fallback values at boundaries.
  • Treat Java interop as untrusted: platform types can still be null.
  • Use @Nullable / @NotNull annotations on Java code consumed by Kotlin.

SQL Injection

  • Use Exposed DSL or JPA with parameterized queries. Never concatenate input.
  • Use PreparedStatement if writing raw JDBC.
  • Use CriteriaBuilder or Exposed conditions for dynamic query construction.
  • Audit @Query(nativeQuery = true) for parameter interpolation risks.

Serialization

  • Use kotlinx.serialization with @Serializable for compile-time safety.
  • Use Json { ignoreUnknownKeys = true } but validate after deserialization.
  • Never use Java ObjectInputStream for deserialization (RCE risk).
  • Restrict polymorphic deserialization to known sealed class subtypes.

Authentication

  • Use Spring Security or Ktor Authentication plugin. Do not roll your own.
  • Hash passwords with BCrypt or Argon2. Never store plaintext.
  • Use short-lived JWTs (15 min) with refresh token rotation.
  • Validate JWT signature, issuer, audience, and expiration on every request.

Coroutine Security

  • Use withTimeout() to prevent unbounded coroutine execution (DoS vector).
  • Use Mutex for critical sections. Do not use synchronized in suspend functions.
  • Propagate security context through CoroutineContext elements.
  • Cancel coroutine scopes on authentication failure or session expiry.

Secrets Management

  • Use environment variables or Vault for secrets. Never hardcode.
  • Use @ConfigurationProperties with injected secrets, not string literals.
  • Never log request headers containing Authorization tokens.
  • Use separate configuration profiles for dev/staging/prod secrets.

Dependencies

  • Use Dependabot or Renovate for automated dependency updates.
  • Run OWASP Dependency-Check or Gradle dependencyCheckAnalyze.
  • Audit transitive dependencies with gradle dependencies.
  • Pin dependency versions. Avoid dynamic versions like 1.+.

Logging

  • Use parameterized logging: logger.info("User {} logged in", userId).
  • Never log passwords, tokens, or PII.
  • Sanitize user input before logging to prevent log injection.
  • Use structured logging (JSON) for machine-parseable audit trails.

Kotlin Testing

Framework

  • Use JUnit 5 as the test runner.
  • Use Kotest for Kotlin-idiomatic BDD-style testing (alternative).
  • Use MockK for mocking (Kotlin-native, supports coroutines).
  • Use Testcontainers for integration tests with external services.

File Naming

  • Test files: FooTest.kt in src/test/kotlin/ mirroring source package.
  • Integration tests: FooIT.kt or use @Tag("integration").
  • Use @Nested inner classes to group related test cases.

Structure

  • Use @DisplayName for human-readable test names.
  • Use backtick function names for readable test names: `returns 404 when user not found`.
  • Use @BeforeEach for per-test setup. Avoid shared mutable state.
  • Use @ParameterizedTest with @MethodSource for table-driven tests.

MockK

  • Use mockk<UserRepository>() to create mocks.
  • Use every { mock.find(any()) } returns user for stubbing.
  • Use coEvery { ... } and coVerify { ... } for coroutine mocking.
  • Use spyk() for partial mocks on real objects.
  • Use slot<T>() and captured to inspect arguments.
  • Clear mocks in @AfterEach to prevent state leakage.

Coroutine Testing

  • Use runTest { } from kotlinx-coroutines-test for coroutine tests.
  • Use TestDispatcher to control coroutine execution timing.
  • Use advanceUntilIdle() to complete all pending coroutines.
  • Use turbine library for testing Flow emissions.

Assertions

  • Use AssertJ or Kotest assertions for fluent, readable checks.
  • Use shouldBe, shouldThrow, shouldContain (Kotest matchers).
  • Use assertSoftly { } to collect multiple assertion failures.
  • Use assertThrows<FooException> { ... } for exception testing.

Test Data

  • Use factory functions for test data: fun aUser(name: String = "Ada") = User(...).
  • Use default parameters for minimal test data setup.
  • Use copy() on data classes for variations of base test objects.
  • Use faker library for realistic test data generation.

Spring Integration

  • Use @SpringBootTest with @AutoConfigureMockMvc for API tests.
  • Use @WebMvcTest for controller-only tests (faster).
  • Use @MockkBean instead of @MockBean for MockK integration.
  • Use @Transactional on test classes for automatic rollback.

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

  • 提供全面的Kotlin编码规范,涵盖风格、框架、安全、测试等多个维度
  • 内容详实,对Kotlin开发者具有极高的实用价值和指导意义
触发精准90/100

亮点

  • 触发词精准完整,覆盖.kt、.kts、build.gradle.kts、Ktor、Jetpack Compose、协程、kotlinx等多种变体
  • 边界清晰,不易误触或漏触
结构规范90/100

亮点

  • 结构清晰,分章节详细,有明确的章节划分和出口条件
  • frontmatter完整,单文件未超限,易于理解执行流程
执行可靠95/100

亮点

  • 内容来源明确,参数正确,覆盖主要异常情况
  • 无不可逆操作风险,执行可靠性高
证据可验 (前四项均值)93/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。