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?

Kotlinのrequireを使ってみる

1
Posted at

Kotlinには、条件を満たさない場合に例外を投げるための関数としてrequireが用意されています。

if文でも同じことはできますが、requireを使うことで
コードの意図が明確になります。

書き方

.kt
require(count >= 0)

条件がfalseの場合、IllegalArgumentExceptionを投げる
「渡された値が不正」であることを表す
主に引数や外部入力の検証に使います

requireの典型的な使いどころは、関数の引数チェック、外部入力のバリデーションなどです。
信用できない値に対して使います。

Exceptionを投げるため満たさない場合処理を続行できない条件等に使用箇所を限定して、意図がわかりやすくなる場合に使用する検討をしてみるのもいいかもしれないです。

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?