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

Jetpack Compose で nullable をそのまま UI に流すと壊れやすくなる話 〜「安全なはずの null 許容」がエラーの温床になる理由〜

Posted at

はじめに

Jetpack Compose で開発していると、
型的には問題なさそうなコードなのに、
なぜかエラーが増えていく場面に遭遇することがあります。

その原因の一つが、nullable な値をそのまま UI に渡していることでした。

本記事では、Compose 開発で見落としがちな
nullable と UI の関係について整理します。

解説

Kotlin では nullable 型を使うことで、
null 安全性を高めることができます。

しかし Compose の UI では、
nullable をそのまま扱うことで、

UI 側に条件分岐が増える

表示ロジックが散らばる

エラーの影響範囲が広がる

といった問題が起きやすくなります。

特に、

nullable を直接 Text() や選択 UI に渡す

null チェックを画面ごとに持たせる

といった書き方は、
後から修正しづらい状態を作りがちでした。

そのため、
nullable は UI に入る前に吸収し、
UI 側は「表示できる値だけを扱う」
という方針に落ち着きました。

この形にすることで、

型エラーの連鎖

修正時の影響範囲

想定外の UI 崩れ

が明らかに減りました。

まとめ

nullable 自体が悪いわけではありません。
ただし、Compose では
null をどこまで通すかが安定性に直結します。

null は境界で処理する

UI は表示に専念させる

この前提を置くだけでも、
Compose 開発はかなり扱いやすくなります。

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