1
1

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】Kotlin の inline class(インラインクラス)について解説します

Last updated at Posted at 2025-09-15

1. 概要

inline class は Kotlin 1.3 で導入された機能で、単一の値をラップする軽量クラス を定義できます。
例えば IDEmailPhoneNumber などを StringInt のまま扱うと混同しやすいですが、専用の型にすることで安全に管理できます。

  • 型安全:同じ String でも EmailPhoneNumber を区別できる
  • パフォーマンス:コンパイル時にインライン化され、余計なオブジェクトを生成しない

2. 定義方法

Kotlin 1.3〜1.4(旧: inline class)

inline class Email(val value: String)
inline class UserId(val id: Int)

Kotlin 1.5 以降(新: value class)

@JvmInline
value class Email(val value: String)

@JvmInline
value class UserId(val id: Int)

注意:

  • inline class は Kotlin 1.5 以降 非推奨
  • 代わりに value class が正式 に使われます

3. 使用例

@JvmInline
value class UserId(val id: Int)

fun getUserName(userId: UserId): String {
    return "User #${userId.id}"
}

fun main() {
    val userId = UserId(100)
    println(getUserName(userId)) // User #100
}

実行時には UserId はただの Int として扱われ、余分なオブジェクト生成は行われません。


4. 制約

  • フィールドは 1つのみ
  • 継承できないopen / abstract / sealed は不可)
  • init ブロックなし(バリデーションはファクトリ関数で行う)
  • UserId? のような nullable 型はボックス化 される場合がある

5. よくある用途

  • 型安全な ID(例: CustomerId, OrderId
  • 単位付きの値(例: Meter, Second
  • API 層とドメイン層での型区別

まとめ

  • inline class = Kotlin 1.3 で導入された軽量ラッパー(すでに非推奨)
  • value class = Kotlin 1.5 以降の正式版。今後はこちらを使うべき

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?