Kotlin PatternsSAFE
The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
Overview
The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
649b2d7452ebOBSERVED · 2026-09-21What it tells the agent
The instruction file, verbatim from the audited commit — this is the text the model reads, and the surface the audit's instruction layer examines. Quoted here so you can judge it without cloning anything.
---
name: kotlin-patterns
description: コルーチン、null 安全性、DSL ビルダーを使用して堅牢・効率的・保守性の高い Kotlin アプリケーションを構築するための慣用的な Kotlin パターン、ベストプラクティス、規約。
origin: ECC
---
# Kotlin 開発パターン
堅牢・効率的・保守性の高いアプリケーションを構築するための慣用的な Kotlin パターンとベストプラクティス。
## 使用するタイミング
- 新しい Kotlin コードを書く
- Kotlin コードをレビューする
- 既存の Kotlin コードをリファクタリングする
- Kotlin モジュールまたはライブラリを設計する
- Gradle Kotlin DSL ビルドを設定する
## 動作の仕組み
このスキルは 7 つの主要領域にわたって慣用的な Kotlin の規約を適用します: 型システムとセーフコール演算子を使用した null 安全性、`val` とデータクラスの `copy()` によるイミュータビリティ、網羅的な型階層のためのシールドクラスとインターフェース、コルーチンと `Flow` による構造化並行性、継承なしで振る舞いを追加する拡張関数、`@DslMarker` とラムダレシーバーを使用した型安全 DSL ビルダー、そしてビルド設定のための Gradle Kotlin DSL。
## 使用例
**Elvis 演算子を使用した null 安全性:**
```kotlin
fun getUserEmail(userId: String): String {
val user = userRepository.findById(userId)
return user?.email ?: "[email protected]"
}
```
**網羅的な結果のためのシールドクラス:**
```kotlin
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 を使用した構造化並行性:**
```kotlin
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. Null 安全性
Kotlin の型システムは null 可能型と非 null 型を区別します。これを最大限に活用してください。
```kotlin
// 良い例: デフォルトで非 null 型を使用
fun getUser(id: String): User {
return userRepository.findById(id)
?: throw UserNotFoundException("User $id not found")
}
// 良い例: セーフコールと Elvis 演算子
fun getUserEmail(userId: String): String {
val user = userRepository.findById(userId)
return user?.email ?: "[email protected]"
}
// 悪い例: null 可能型を強制アンラップ
fun getUserEmail(userId: String): String {
val user = userRepository.findById(userId)
return user!!.email // null の場合 NPE をスロー
}
```
### 2. デフォルトでイミュータブル
`var` より `val` を優先し、ミュータブルコレクションよりイミュータブルコレクションを優先してください。
```kotlin
// 良い例: イミュータブルデータ
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. 式ボディと単一式関数
簡潔で読みやすい関数には式ボディを使用してください。
```kotlin
// 良い例: 式ボディ
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 -> "Unknown status: $code"
}
// 悪い例: 不要なブロックボディ
fun isAdult(age: Int): Boolean {
return age >= 18
}
```
### 4. 値オブジェクトのためのデータクラス
主にデータを保持する型にはデータクラスを使用してください。
```kotlin
// 良い例: 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 cannot be blank" }
}
}
@JvmInline
value class Email(val value: String) {
init {
require('@' in value) { "Invalid email: $value" }
}
}
fun getUser(id: UserId): User = userRepository.findById(id)
```
## シールドクラスとインターフェース
### 制限された階層のモデリング
```kotlin
// 良い例: 網羅的な 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("Still loading")
}
```
### API レスポンス用シールドインターフェース
```kotlin
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
}
```
## スコープ関数
### それぞれの使用タイミング
```kotlin
// let: null 可能またはスコープ付き結果を変換
val length: Int? = name?.let { it.trim().length }
// apply: オブジェクトを設定する(オブジェクトを返す)
val user = User().apply {
name = "Alice"
email = "[email protected]"
}
// also: 副作用(オブジェクトを返す)
val user = createUser(request).also { logger.info("Created user: ${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()
}
```
### アンチパターン
```kotlin
// 悪い例: スコープ関数のネスト
user?.let { u ->
u.address?.let { addr ->
addr.city?.let { city ->
println(city) // 読みにくい
}
}
}
// 良い例: セーフコールチェーンを使用
val city = user?.address?.city
city?.let { println(it) }
```
## 拡張関数
### 継承なしで機能を追加
```kotlin
// 良い例: ドメイン固有の拡張
fun String.toSlug(): String =
lowercase()
.replace(Regex("[^a-z0-9\\s-]"), "")
.replace(Regex("\\s+"), "-")
.trim('-')
fun Instant.Trust audit
SAFEgrade B · trust 89/100 Nothing in the source contradicts what it says it does. Grade A is reserved for packages that have also passed the behavioural sandbox.
| Layer | What it checks | Result |
|---|---|---|
| L0 | Provenance & inventory | PASS |
| L1 | Static analysis of the code | NA |
| L2 | Instruction surface (what it tells the agent) | PASS |
| L3 | Class-specific surface | PASS |
| L4 | Behavioural (sandbox) | SKIPPED |
What the source does
- Filesystem
- none-observed
- Network
- none-observed
- Shell
- none-observed
- Dependencies
- pinned
- Secrets in source
- none-found
Findings (0)
No findings outside the package's declared scope.
Gates applied: no_behavioural_pass.
649b2d7452ebfull audit observations/trust-audit/skill/affaan-m__kotlin-patterns.json · Report an issue / request a re-scanAudit history
Every audit this skill has had.
| Date | Source | Verdict | Grade | Score | Change |
|---|---|---|---|---|---|
| 2026-09-21 | 649b2d7452eb | SAFE | B | 89 | first audit |
Questions
What does the Kotlin Patterns skill do?
The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
Is Kotlin Patterns safe to install?
The audit found nothing in the source that contradicts what it says it does, and graded it B (89/100). Grade A is held back for packages that have also passed a sandboxed behavioural run, which is why a clean skill reads B.
What can Kotlin Patterns access on my machine?
The audit observed no filesystem, network or shell use at all in its source.
How current is this page?
The grade is for one exact copy of the source (649b2d7452eb), read on 2026-09-21. The repository is watched, and a new audit runs when it changes — this is the first audit.