val numList = mutableListOf<Int>(1,2,3,4)

1. for

반복하여 List의 원소 값을 출력

for(item in numList)
{
    println(item)
}
/*
출력값
1
2
3
4
*/

1-1. 인덱스와 원소 값을 함께 출력

for( (index, item) in numList.withIndex())
{
    println("index: $index, value: $item")
}

/*
출력값
index: 0, value: 1
index: 1, value: 2
index: 2, value: 3
index: 3, value: 4
*/

1-2. 반복 횟수를 지정

 

until은 크기 - 1만큼을 뜻한다.

for(i in 0 until numList.size) // 0 부터 numList의 크기 - 1 만큼 반복
{
    println( "until: $i" )
}

 

step: 증가 값을 지정

0부터 2씩 증가하여 i에 대입한다.

numList의 인덱스를 0, 2, 4, 6 ... 이런식으로 접근하여 사용한다.

for(i in 0 until numList.size step (2))
{
    println( "step: $i" )
}

 

downTo 값을 감소시키면서 반복

for ( i in numList.size - 1 downTo (0) )
{
    println( "downTo: $i" )
}

 

downTo, step: step값 만큼 감소 시켜서 반복

for ( i in numList.size - 1 downTo (0) step (2))
{
    println( "downTo step: $i" )
}

 

배열.size 마지막을 포함한다

for(i in 0..numList.size)
{
    println("..: $i")
}

2. foreach

numList.forEach {
    println(it)
}

numList.forEach { item ->
    println(item)
}

2-1. index를 포함한 forEach

numList.forEachIndexed { index, item ->
    println("index: $index, value: $item")
}

3. While

반복문 내부에 조건을 거짓으로 만드는 탈출 문장이 있어야 끝나게 된다.

var W1: Int = 0
var W2: Int = 6

while (W1 < W2)
{
    ++W1
    println("$W1: W1")
}

 

3-1. Do While

최소 1번의 실행을 보장하는 반복문

var W3: Int = 0
var W4: Int = 6

do 
{
    println("$W3: W4")
    ++W3
}while(W3 < W4)

 

'Android > Kotlin' 카테고리의 다른 글

kotlin 12. Class - 선언, 생성자  (0) 2020.08.11
kotlin 09. Array (배열)  (0) 2020.08.11
kotlin 08. Control flow 2 (제어흐름 when)  (0) 2020.08.11
kotlin 07. Control flow (제어흐름 if)  (0) 2020.08.11
kotlin 06. Operator (연산자)  (0) 2020.08.11

+ Recent posts