0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Kotlin】infix × inline × reified」で実現する型安全なユーティリティ設計

Posted at

はじめに

Kotlin の強力な3要素

infix(中置記法)
inline(インライン化)
reified(実行時に型情報を保持)

を組み合わせることで、型安全かつ表現力豊かなDSL風ユーティリティを作ることができます。


この記事のゴール

この記事を読めば、次のような関数を自作できるようになります

val intent = createIntent<MainActivity>() withExtra ("userId" to 42)

1. 基本構文のおさらい

infix

中置記法を可能にする構文糖衣。

infix fun Int.times(str: String) = str.repeat(this)
println(2 times "Bye ") // Bye Bye 

inline + reified

インライン化によって「型パラメータを実行時に扱える」ようにします。

inline fun <reified T> printTypeName() {
    println(T::class.simpleName)
}

printTypeName<String>() // → String

通常のジェネリクスでは 型消去(type erasure) により実行時の型情報は失われますが、
reified を付けることで実行時に T::class が利用可能になります。


2. 3つを組み合わせると何ができる?

型安全な Intent ヘルパーの例

Android 開発では Activity を開く際に Intent を作成します。

通常は次のように書きます:

val intent = Intent(context, MainActivity::class.java)
intent.putExtra("userId", 42)

これを Kotlin らしく書き直すと


infix × inline × reified を使った型安全設計

inline fun <reified T> createIntent(context: Context): Intent {
    return Intent(context, T::class.java)
}

infix fun Intent.withExtra(pair: Pair<String, Any>): Intent = apply {
    val (key, value) = pair
    when (value) {
        is Int -> putExtra(key, value)
        is String -> putExtra(key, value)
        is Boolean -> putExtra(key, value)
        else -> throw IllegalArgumentException("Unsupported type: ${value::class}")
    }
}

実際の使い方

val intent = createIntent<MainActivity>(context) withExtra ("userId" to 42)
startActivity(intent)

自然言語のように読めて、型安全 + 簡潔 + エレガント


3. 仕組み図


まとめ

キーワード 役割
infix 中置記法でDSL風表現を作る
inline 関数呼び出しを展開してパフォーマンス向上
reified 実行時にも型情報を利用可能にする
組み合わせ効果 型安全で自然言語のように読めるユーティリティが実現可能

Kotlin の infix × inline × reified の組み合わせは、
API 設計・DSL 設計・Android ユーティリティ設計において最強クラスの武器です。

この3つを活用すると、
単なるコードを**「読みやすい表現」**に変えることができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?