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?

requireNotNullよりも適切な選択肢

Posted at

Android開発でアダプターやダイアログを実装している時にrequireNotNull()を使用するよりも適切な関数を教えていただいたので、そちらをメモします。

requireNotNull

requireNotNullはKotlin標準ライブラリに用意されている関数で、nullチェックを簡潔に行うために使用されます。

  • 引数がnullであればIllegalArgumentExceptionをスローする
  • null でなければその値をそのまま返す
val safeValue = requireNotNull(value) { "title is required" }

requireArguments()

requireArgumentsはAndroidのFragmentクラスに用意されている関数で、arguments が null でないことを保証するために使用されます。

  • argumentsがnullの場合はIllegalStateExceptionをスローする
  • nullでなければそのまま返す
val title = requireArguments().getString("title")

requireContext()

requireContext()はFragmentがContextにアタッチされていることを前提として、Contextを返すメソッドです。

  • Fragment のcontextプロパティは nullable(Context?)
  • nullだった場合(未アタッチ状態)はIllegalStateExceptionをスローする
// SharedPreferences を取得する
val prefs = PreferenceManager.getDefaultSharedPreferences(requireContext())
// Toast を表示する
Toast.makeText(requireContext(), "Hello!", Toast.LENGTH_SHORT).show()

requireNotNullの場合だとエラーが起きた時にIllegalArgumentExceptionとなり、どこで問題が起きたか曖昧だが、requireArgumentsやrequireContextだとエラーが明確に分かります。requireNotNull() は汎用的すぎるため、argumentsやcontextを取得する場合は適切な関数を使用します。

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?