Kotlin list for문 - index loop

Notepad96

·

2020. 11. 22. 15:26

300x250

 

 

 

 


1. For loop

 

Kotlin에서 for문은 기본적으로 Java의 향상된 for문 처럼 원소로 접근한다.

 

 

 

따라서 index로 for문을 반복하기 위해서는

 

List에 존재하는 indices 프로퍼티를 사용하거나

 

forEachIndexed 사용할 수 있다.

 

 

 

 


2. 코 드

환경 : Kotlin Version = 1.4.10, JVM

fun main(args : Array<String>) {
    val ml = mutableListOf(1, 2, 3, 4, 5)

    // 리스트 출력
    print("1. ")
    println(ml)

    // 각 원소 for문
    print("2. ")
    for(a in ml) {
        print("$a ")
    }
    println()

    // index로 for문
    print("3. ")
    for(i in 0..ml.lastIndex) {
        print("${i}:${ml[i]} ")
    }
    println()

    // index로 for문
    print("4. ")
    for(i in ml.indices) {
        print("${i}:${ml[i]} ")
    }
    println()


    // forEach
    print("5. ")
    ml.forEach { print("$it ") }
    println()


    // forEach + index
    print("6. ")
    ml.forEachIndexed{ index, value ->
        print("${index}:${value} ")
    }
    println()

}

 

결 과

 

 

 

- 2번은 기본적으로 사용하는 for문으로서 각 원소의 대하여 루프를 반복한다.

 

해당 방법으로는 리스트 원소의 값을 변경할 수 없으며

 

 

값을 변경해주기 위하여 index로 for 루프를 돌아서 변경해 줄 수 있다.

 

 

 

 

 

- Index로 for문을 돌기 위해서는 3, 4, 6번의 방법을 사용할 수 있다.

 

 

3번은 '0..lastIndex'의 IntRange로서 lastIndex 프로퍼티를 사용하며

 

 

4번indices 프로퍼티를 사용하며

 

 

6번forEachIndexed 를 사용하여 각 index의 접근하여 for문을 반복할 수 있다.

 

 

 

 

 

 


3. 참 조

 

 

forEachIndexed - Kotlin Programming Language

 

kotlinlang.org

 

300x250