0
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】コピペで使える「null」を消すテクニック頻出順40

0
Last updated at Posted at 2026-07-31

🧑🏻‍💻 1. Non-null を基本にする

// 悪い
val name: String?

// 良い
val name: String

Nullable を作らないことが最も重要。

🧑🏻‍💻 2. DTOだけ Nullable

data class UserResponse(
    val name: String?
)

外部データだけ Nullable にする。

🧑🏻‍💻 3. Domain は Non-null

data class User(
    val name: String
)

アプリ内部では Non-null を維持する。

🧑🏻‍💻 4. Repositoryで吸収する

fun load(): User =
    api.load()?.toUser() ?: User.EMPTY

Repository より先へ Nullable を持ち込まない。

🧑🏻‍💻 5. デフォルト値を使う

data class User(
    val name: String = ""
)

初期値で null を不要にする。

つづく...

🧑🏻‍💻 引用

0
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
0
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?