28
25

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 5 years have passed since last update.

Kotlinでループ処理

Posted at

KotlinのVersion

1.3.31

forループ

for (変数 in イテレータ)の書式で記述する。イテレータにはIteratorインターフェースを実装したオブジェクトを指定する。このあたりはJava等でも同じ。

Hello.kt
fun main() {

    // ふつーのループ
    for (i in 1..100) println(i)

    // 上記はJavaっぽくこうも書ける
    for (i in 1..100) {
        println(i)
    }

    // 配列を使った例
    val array = arrayOf("aa", "bb", "cc", "dd", "ee")
    for (i in array) println(i)

    // downToを使えばループ終端(ここでは0)まで減らしながらループを回せる
    for (i in 10 downTo 0 step 1) println(i)

    // Mapもこんな形でループを回せる(mapOfはMapインスタンスを生成)
    var map = mapOf("1" to "Tanaka", "2" to "sasaki")
    for ((k, v) in map) println("$k : $v")
}

whileループ

もちろんwhile、do~whileも可能。

Hello.kt
fun main() {

    var i = 0
    while (i != 3) {
        println(i)
        i += 1
    }

    do {
        println(i)
        i -= 1
    } while (i != 0)
}

高階関数を用いたループ

高階関数(repeatやforeach)を用いたループも記述できる。

Hello.kt
fun main() {

    // repeat関数は、ループ回数を指定するだけでその回数分ループしてくれる。繰り返し回数はitで参照ができる。
    repeat(10) {
        println(it)
    }

    // もちろんこういった書き方も可能
    val array = arrayOf(1, 2, 3, 4, 5)
    repeat(array.size) {
        println(it)
    }

    // 配列やコレクションのループにはforeach関数が利用できる。。繰り返し対象の要素はitで参照ができる。
    array.forEach {
        println(it)
    }
}
28
25
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
28
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?