일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- dfs
- spring cloud
- BFS
- 설계
- code refactoring
- api-gateway
- netflix
- spring cloud netflix zuul
- 단위테스트
- forkandjoinpool #threadpool #jvm #async #non-blocking
- container image #docker #layer #filesystem #content addressable
- docker
- 탐색
- java #jvm #reference #gc #strong reference
- Spring Data Redis
- unit
- 서비스스펙
- reactive
- zuul
- spring cloud netflix eureka
- Eureka
- microservice architecture
- springcloud
- Java
- netflix eureka
- unittest
- test
- Dynamic Routing
- spring cloud netflix
- Today
- Total
phantasmicmeans 기술 블로그
3. Kotlin - Control-Flow 본문
Control Flow: if, when, for, while
- 위 control flow의 항목들은 익숙한 것들이다보니 모든 내용을 다룰 필요는 없어보이니..
- https://kotlinlang.org/docs/reference/control-flow.html
If
코틀린에서 if는 expression으로 간주 될 수 있다. 즉 값을 반환할 수 있다는 말이다. 삼항 연산자를 대신할 수 있는 이유도 이 때문인데 아래 코드를 보자
// Traditional usage
var max = a
if (a < b) max = b
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// As expression!! 값 반환
val max = if (a > b) a else b
if는 값을 반환할 수 있으므로, 마지막 val max = if (a > b) a else b
의 경우 java의 삼항 연산자를 대신할 수 있게된다.
또한 expression으로 간주되기에 아래와 같은 경우 java처럼 return을 붙이지 않아도 된다.
val max = if (a > b) {
print("Choose a")
a // return
} else {
print("Choose b")
b // return
}
When 구문
Java의 switch 구문 대신 코틀린은 더 유연한 when 구문을 제공한다. when은 모든 브랜치를 순서대로 탐색하며 조건을 만족하는지 살핀다.
코틀린의 when도 expression으로 사용할 수 있는데 아래 코드는 when이 expressioin으로 사용된 경우이고 값을 반환하니 return 문으로 활용할 수 있다.
fun whenAsExpression(x: Int): String {
return when (x) {
1 -> "1"
2 -> "2"
3 -> "3"
4 -> "4"
else -> "0"
}
}
fun main() {
println(whenTest1(3))
}
또한 값을 반환하니 single expression function으로도 사용할 수 있다.
fun whenAsSingleExpression(x: Int): String = when (x) {
1 -> "1"
2 -> "2"
3 -> "3"
4 -> "4"
else -> "0"
}
또한 when은 다양한 조건들을 처리할 수 있다.
- comma를 통해 여러 condition을 컨트롤
in
or!in
을 활용해 range나 collection에 속하는지 확인is
,!is
를 활용해 타입 체킹- etc ..
fun whenComma(x: Int): String {
return when (x) {
0,1,2 -> "low"
3,4,5 -> "middle"
6,7,8 -> "high"
else -> "-"
}
}
// as statement
fun whenIn(x: Int) {
val validNumbers = listOf<Int>(3,6,9)
when (x) {
in validNumbers -> print("x is valid")
in 1..10 -> print("x is in the range")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
}
fun describe(obj: Any): String = when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
추가로 when은 when은 if-else if 체인을 대체할 수 있는데, when 구문이 인자를 받지 않으면 아래처럼 논리연산으로 처리 된다.
fun whenIfElse(x: Int) {
when {
x % 2 == 1 -> print("x is odd")
x % 2 == 0 -> print("x is even")
else -> print("x is funny")
}
}
For Loops
코틀린의 for-loop는 in
을 사용한다. Java의 foreach loop는 Iterator를 필요로 하는 것 처럼 코틀린도 마찬가지이다.
- Java의 Iterable은 Iterator를 포함하고 있는 것 처럼, 코틀린도 동일하게 구성 되어있다.
- 따라서 자바의 foreach와 동일하다고 볼 수 있고, Iterator를 지원하면 된다.
kotlin - Collections.kt
public interface Iterable<out T> {
/**
* Returns an iterator over the elements of this object.
*/
public operator fun iterator(): Iterator<T>
}
java - Iterable.java
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
Iterator<T> iterator();
... 생략 ...
}
모두 Iterator를 포함하고 있기에 foreach loop를 사용할 수 있고 두 언어 모두 Iterator 명세는 동일하다.
- hasNext()
- next()
Iterator.kt
public interface Iterator<out T> {
/**
* Returns the next element in the iteration.
*/
public operator fun next(): T
/**
* Returns `true` if the iteration has more elements.
*/
public operator fun hasNext(): Boolean
}
Iterator.java
public interface Iterator<E> {
boolean hasNext();
E next();
...
}
아래는 kotlin의 for-loop에 대한 다양한 예시이고, 조금 더 자세한 내용은 여기서 보면 된다.
fun main() {
for (i in 1..1000) {
//println(i)
}
// step, downTo, until 등
for (i in 100 downTo 1 step 2) {
// 98, 96, 94, 92, ...
print(i)
}
val map = TreeMap<Char, String>()
for ((ch, text) in map) {
println("$ch : $text")
}
val list = arrayListOf("java", "kotlin", "javascript")
for ((index, element) in list.withIndex()) {
println("$index : $element")
}
for (c in 'A'..'F') {
print("$c ")
}
}
'Programming > Kotlin' 카테고리의 다른 글
6. Kotlin - Class Inheritance (0) | 2021.01.22 |
---|---|
5. Kotlin - Class (0) | 2021.01.22 |
4. Kotlin - Return and Jumps (0) | 2021.01.22 |
2. Kotlin - Null Safety (0) | 2021.01.22 |
1. Kotlin - Variables, Functions (0) | 2021.01.22 |