Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
29 | 30 |
Tags
- elementAt
- lifecycle
- recyclerview
- map
- Kotlin
- MINUS
- function
- AWS
- enum
- list
- Service
- docker-compose
- LiveData
- react native
- 생명주기
- docker
- Swift
- vuex
- class component
- Generic
- Interface
- mongoose
- Foreign Key
- CLASS
- ReactNative
- animation
- Filter
- ConstraintLayout
- union
- collection
Archives
- Today
- Total
개발 일기
if , when , for , while ? 본문
if :)
코틀린에서는 if 가 값을 반환합니다.
따라서 삼항 연산자는 존재 하지 않습니다. ex) condition ? then : else
그래서 다음과 같이 전통적인 방법과 표현식을 사용한 방법으로 나눌수 있습니다.
// 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
when :)
when은 흔히 아는 switch 문과 비슷합니다.
일부 분기 조건이 충족될 때까지 모든 분기를 순차적으로 탐색합니다.
when도 마찬가지로 expression 또는 statement로 사용할수 있습니다.
else는 모든 조건을 탐색을 했을 때 충족이 안되면 탑니다.
expression을 사용시 else문은 필수입니다.
예시
when (x) {
0, 1 -> print("x == 0 or x == 1")
else -> print("otherwise")
}
when (x) {
parseInt(s) -> print("s encodes x")
else -> print("s does not encode x")
}
when (x) {
in 1..10 -> print("x is in the range") // range 포함 여부
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
// 특정한 타입인지 체크 할수도 있습니다.
fun hasPrefix(x: Any) = when(x) {
is String -> x.startsWith("prefix")
else -> false
}
// 인수에 아무값도 넣지 않으면 boolean 표현식입니다. 따라서 True이면 실행 입니다.
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}
// kotlin 1.3 부터 다음과 같이 가능합니다.
fun Request.getBody() =
when (val response = executeRequest()) {
is Success -> response.body
is HttpError -> throw HttpException(response.status)
}
For Loops :)
for 문은 주어진 값들을 반복하는데에 쓰입니다.
간단하게는 아래와 같이 사용이 됩니다.
for (item in collection) print(item)
for (i in 1..3) {
println(i)
}
//1
//2
//3
for (i in 6 downTo 0 step 2) {
println(i)
}
//6
//4
//2
//0
for (i in array.indices) {
println(array[i])
}
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
While Loops :)
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
'컴퓨터 언어 > kotlin' 카테고리의 다른 글
Interface ? (0) | 2020.04.17 |
---|---|
Properties and Fields ? (0) | 2020.04.16 |
class ? (0) | 2020.04.15 |
Idioms (관용구) (0) | 2020.04.11 |
기본 타입? (0) | 2020.03.10 |
Comments