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?

More than 3 years have passed since last update.

【kotlin】forEach ラベル構文

Posted at

■forEachとは

配列やリストの要素を一つづつ取り出して処理を行うループ処理のためのものです。

例:
配列の数値全てに1を足したい。

例2:
配列の中に特定の文字列が存在するか

■基本的な使い方

fun main() {
 val nums = arrayOf(1,2,3,4,5)
 //ラムダ式で引数は単一なので省いている。
 nums.forEach{print(it)}
}

//結果:  1、2、3、4、5

■returnを使ってみる。

if文で数字が7になればreturnしてジャンプして8,9,10,
println("ラムダ式を終了しました。") が表示されて欲しい。
つまりこう言う結果が欲しい
//結果: 1,2,3,4,5,6,8,9,10,ラムダ式を終了しました。

しかしreturnを使えばforEachだけではなくmain()関数も抜けて関数全体が終了してしまう。

fun main() {
 (1..10).forEach {
       if(it == 7) return
     println(it)
   }
 println("ラムダ式を終了しました。") 
}
//結果: 1,2,3,4,5,6

■ラベル構文

kotlinのデフォルトの設定とは違う場所にジャンプするもの

ラムダ式だけをジャンプする。
forEachの横に loop@
returnの横に @loop
の様に書けば
ラムダ式のみをジャンプする事ができる。

fun main() {
 (1..10).forEach loop@{
       if(it == 7) return@loop
     println(it)
   }
 println("ラムダ式を終了しました。") 
}

//結果: 1,2,3,4,5,6,8,9,10,ラムダ式を終了しました。

■ラムダ式を引数に取る高階関数を名前をラベル構文に指定してもいい。

▼上記と違う書き方処理は同じ
returnの横に高階関数の@forEachを書く

fun main() {
 (1..10).forEach{
       if(it == 7) return@forEach
     println(it)
   }
 println("ラムダ式を終了しました。") 
}

//結果: 1,2,3,4,5,6,8,9,10,ラムダ式を終了しました。
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?