1. Using ranges
** in operator 를 사용하여,
** 범위내 수인지 체크
1 2 3 4 5 6 7 | fun main(args: Array<String>) { val x = 10 val y = 9 if (x in 1..y+1) { println("fits in range") } } | cs |
** 범위를 넘어서는지 체크
1 2 3 4 5 6 7 8 9 10 | fun main(args: Array<String>) { val list = listOf("a", "b", "c") if (-1 !in 0..list.lastIndex) { println("-1 is out of range") } if (list.size !in list.indices) { println("list size is out of valid list indices range too") } } | cs |
** 범위내 반복
1 2 3 4 5 | fun main(args: Array<String>) { for (x in 1..5) { print(x) } } | cs |
** 범위내 정해진 step만큼 반복
1 2 3 4 5 6 7 8 9 | fun main(args: Array<String>) { for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) } } | cs |
2. Using collections
** collection 내 반복
1 2 3 4 5 6 | fun main(args: Array<String>) { val items = listOf("apple", "banana", "kiwifruit") for (item in items) { println(item) } } | cs |
** in operator를 사용하여,
collection이 object를 포함하는지 체크
1 2 3 4 5 6 7 | fun main(args: Array<String>) { val items = setOf("apple", "banana", "kiwifruit") when { "orange" in items -> println("juicy") "apple" in items -> println("apple is fine too") } } | cs |
** filter와 map collection에 lambda expression 사용
1 2 3 4 5 6 7 8 | fun main(args: Array<String>) { val fruits = listOf("banana", "avocado", "apple", "kiwifruit") fruits .filter { it.startsWith("a") } .sortedBy { it } .map { it.toUpperCase() } .forEach { println(it) } } | cs |
'Kotlin > Basic Syntax' 카테고리의 다른 글
8. Creating basic classes and their instances (0) | 2018.05.31 |
---|---|
6. Using for loop & while loop & when expression (0) | 2018.05.31 |
5. Using Type checks & Automatic casts (0) | 2018.05.31 |
4. Using nullable values and Checking for null (0) | 2018.05.31 |
3. Using String templates & Conditional expressions (0) | 2018.05.31 |