글
[Kotlin] 제어문 for , forEach , range , repeat , when
Android (Kotlin)
2020. 9. 13. 18:12
for in
예 1.) ===============================================
for (i in 0..5) {
print(i)
}
예 2.) ===============================================
val items = listOf(10, 20, 30, 40)
for (i in items)
println("value is $i")
//Following is printed to the console.
value is 10
value is 20
value is 30
value is 40
예 3. index 출력 "indices" ============================
val items = listOf(10, 20, 30, 40)
for (i in items.indices)
println("value is $i")
//Following is printed to the console:
value is 0
value is 1
value is 2
value is 3
예 4.) index 와 element 출력 "withIndex()" =============
val items = listOf(10, 20, 30, 40)
for ((i,e) in items.withIndex())
println("the index is $i and the element is $e")
//Following is printed on the console:
the index is 0 and the element is 10
the index is 1 and the element is 20
the index is 2 and the element is 30
the index is 3 and the element is 40
forEach [ Range " .. 연산자 " ]
(2..5).forEach{
println(it)
}
//or
(2..5).forEach{
i -> println(i)
}
//Following is printed on the console:
2
3
4
5
존재 여부 " in , !in"
var x = 5
if(x in 1..10)
{
print("x exists in range") //this gets printed
}
else{
print("x does not exist in range")
}
x = 15
if(x !in 1..10)
{
print("x does not exist in range") //this gets printed
}
else{
print("x does exist in range")
}
Range ..는 역순으로 사용할 수 없음. --> 10..0 처럼 거꾸로 사용 못함.
여기에서 downTo키워드를 사용
var x = 5
if(x in 10 downTo 1)
{
print("x exists in range") //this gets printed
}
else{
print("x does not exist in range")
}
for (i in 5 downTo 0)
print(i) //543210
마지막 요소를 제외 "until"
for (i in 1 until 4) {
print(i)
}
//prints 123
단계적으로 범위를 탐색 "step"
for (i in 1..5 step 3) print(i) // prints 14
for (i in 4 downTo 1 step 2) print(i) // prints 42
N번 반복 실행 "repeat"
repeat(3) {
println("Hello World!")
println("Kotlin Control Flow")
}
선택, 분기분 "when"
예 1.)
var num = 10
when (num) {
0 -> print("value is 0")
5 -> print("value is 5")
else -> {
print("value is neither 0 nor 5") //this gets printed.
}
}
예 2.) until
var valueLessThan100 = when(101){
in 1 until 101 -> true
else -> {
false
}
}
print(valueLessThan100) //false
제어문 for , forEach , range , repeat , when
'Android (Kotlin)' 카테고리의 다른 글
[Kotlin] DataClass (0) | 2020.09.14 |
---|---|
[Kotlin] 클래스 정리 (0) | 2020.09.13 |
[Kotlin] let 과 also , Elvis 연산자 와 Null 값 필터링 (0) | 2020.09.13 |
[Kotlin] Array 배열 (0) | 2020.09.13 |
[Kotlin] String 문자열 (0) | 2020.09.13 |