Sunstripe

Kotlinラボ

🌓 テーマ切替

概要

Kotlin は 静的型付けNull安全関数型要素 を併せ持つモダン言語。
JVMAndroid公式Kotlin MultiplatformKotlin/NativeKotlin/JS CoroutinesFlowComposeK2 Compiler

特徴

  • Java との 高い相互運用性(既存資産を活かせる)
  • Null安全拡張関数データクラス 等で簡潔
  • Coroutines による軽量並行処理/Flow によるリアクティブ
  • Compose による宣言的UI(Android/Multiplatform)

主な利用領域

  • Androidアプリ開発(公式推奨)
  • サーバーサイド(Ktor、Spring Boot)
  • マルチプラットフォーム(KMP:iOS/デスクトップ/ウェブ/サーバ)
▶ Hello, Kotlin(ブラウザ実行)

※ネット接続が必要です。JetBrains提供の Kotlin Playground を使用します。


// Kotlin Playground でその場実行
fun main() {
    println("Hello, Kotlin 👋")
    val xs = listOf(1,2,3,4).map { it * it }
    println(xs.joinToString())
}

基本


// 変数・関数・when式
fun greet(name: String?): String {
    val who = name ?: "world"   // null安全(Elvis演算子)
    return when (who.length) {
        in 1..3 -> "Hi, $who"
        else    -> "Hello, $who"
    }
}

data class User(val id: Long, var name: String)

fun main() {
    val u = User(1, "Pluto")
    println(greet(u.name))
}

// 拡張関数とスマートキャスト
fun Any?.asIntOrNull(): Int? = when (this) {
    is Int -> this
    is String -> this.toIntOrNull()
    else -> null
}

fun demo(v: Any?) {
    val i = v.asIntOrNull()
    if (i != null) println(i + 1) // スマートキャストで Int 扱い
}

基礎

テーマ要点
コレクション map/filter/reducesequence による遅延

val evensSquared = (1..10).asSequence()
    .filter { it % 2 == 0 }
    .map { it * it }
    .toList()
スコープ関数 let, run, apply, also, with

data class Box(var w:Int=0,var h:Int=0)
val b = Box().apply { w=100; h=50 }.also { println(it) }

導入

  1. JDK をインストール(推奨: Temurin 17+)
  2. IDE を用意(IntelliJ IDEA / Android Studio)
  3. Gradle Kotlin DSL(build.gradle.kts)でプロジェクト作成

// settings.gradle.kts
rootProject.name = "hello-kotlin"

// build.gradle.kts(JVMアプリの最小構成)
plugins {
    kotlin("jvm") version "2.0.0" // 例。必要に応じて更新
    application
}
repositories { mavenCentral() }
dependencies { testImplementation(kotlin("test")) }
application { mainClass.set("MainKt") }
tasks.test { useJUnitPlatform() }

// src/main/kotlin/Main.kt
fun main() = println("Hello from Kotlin!")

※ バージョンはプロジェクト作成時の最新安定版に合わせて調整してください。

開発現場

非同期:Coroutines/Flow


suspend fun fetch(): List = listOf("A","B")

// ViewModel 等で
val dataFlow = flow {
    emit(fetch())
}.flowOn(Dispatchers.IO)

サーバ:Ktor


// build.gradle.kts 抜粋
dependencies {
    implementation("io.ktor:ktor-server-netty:3.0.0") // 例
    implementation("io.ktor:ktor-server-core:3.0.0")
    implementation("ch.qos.logback:logback-classic:1.5.6")
}

fun Application.module() {
    routing {
        get("/hello"){ call.respondText("Hello Ktor!") }
    }
}

最新情報

📰 Kotlin Blog

🏷️ GitHub Releases

  • ニュース準備中です。

応用

  • DI:Koin / Hilt
  • テスト:JUnit5 / Kotest / MockK
  • Compose Multiplatform:共通UI + プラットフォーム毎のホスト
  • Gradle Kotlin DSL:型安全なビルド設定

発展

Kotlin Multiplatform では、共通コード期待/実装expect/actual)でプラットフォーム差分を吸収します。


// 共通
expect fun platformName(): String
fun greeting() = "Hello from ${platformName()}"

// iOS などプラットフォーム側
actual fun platformName(): String = "iOS"

より具体的に

▶ CLIアプリの最小テンプレ(Gradle Kotlin DSL)

// build.gradle.kts
plugins { kotlin("jvm") version "2.0.0"; application }
repositories { mavenCentral() }
application { mainClass.set("MainKt") }
dependencies { testImplementation(kotlin("test")) }
tasks.test { useJUnitPlatform() }
▶ Ktor ミニAPI(/health エンドポイント)

fun Application.module() {
  routing {
    get("/health"){ call.respond(mapOf("ok" to true)) }
  }
}
▶ Compose Multiplatform:共通UIの雛形(概念)

@Composable
fun App() {
  var count by remember { mutableStateOf(0) }
  Column { Button(onClick={ count++ }) { Text("Clicked $count") } }
}