0
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】takeIfを使ってみる

Last updated at Posted at 2025-06-07

takeIf とは?

takeIf は、条件を満たす場合に自分自身を返し、満たさない場合は null を返すKotlinの標準拡張関数です。

使用方法

val result = value.takeIf { 条件 }
  • 条件が true の場合 → value を返す
  • 条件が false の場合 → null を返す

基本例

val input = "kotlin"
val result = input.takeIf { it.length > 5 }
// result = "kotlin"
val input = "abc"
val result = input.takeIf { it.length > 5 }
// result = null

null許容型と組み合わせる

val email: String? = getInput()
val validEmail = email?.takeIf { it.contains("@") }

他にも便利な使い方があるので試してみてください。
以上です。

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