if
val a = 10
val b = 20
var max = a
if (a < b) max = b
#์คํ๋ฌธ์ด ํ ์ค์ด๋ฉด ๋ธ๋ก ์๋ต๊ฐ๋ฅํ๋ค.
if - else
if (a > b){
max = a
} else{
max = b
}
val max = if (a > b) a else b
#if๋ฌธ์ ์์ฒ๋ผ ์ฌ์ฉํ ์๋ ์๋ค.
when
val x = 1
when (x) {
1 -> println("x == 1")
2, 3 -> println("x == 2 or x == 3")
in 4..7 -> println("4๋ถํฐ 7์ฌ์ด")
!in 8..10 -> println("8๋ถํฐ 10์ฌ์ด๊ฐ ์๋")
else -> {
print("x๋ 1์ด๋ 2๊ฐ ์๋")
}
}
# when์ ๋ค์ํ ๋ฐฉ๋ฒ์ผ๋ก ์ฌ์ฉ๊ฐ๋ฅํ๋ค.
val number = 1
fun isEven(num: Int) = when (num % 2){
0 -> "์ง"
else -> "ํ"
}
println(isEven(number))
๊ฒฐ๊ณผ : ํ
# when๋ฌธ์ ๊ฒฐ๊ณผ๋ฅผ ํจ์์ ๋ฐํ๊ฐ์ผ๋ก ์ฌ์ฉํ ์๋ ์๋ค.
for
val number = arrayOf(1, 2, 3, 4, 5)
for (i in number){
println(i)
}
#๊ฒฐ๊ณผ
1
2
3
4
5
# in ํค์๋๋ฅผ ์ฌ์ฉํด ๋ชจ๋ ์์๋ฅผ i ๋ณ์๋ก ๊ฐ์ ธ์จ๋ค.
// 1~3๊น์ง ์ถ๋ ฅ
for (i in 1..3){
println(i)
}
// 0~10๊น์ง 2๊น์ง ์ฆ๊ฐํ๋ฉฐ ์ถ๋ ฅ
for (i in 0..10 step 2){
println(i)
}
// 10๋ถํฐ 0๊น์ง 2์ฉ ๊ฐ์ํ๋ฉฐ ์ถ๋ ฅ
for (i in 10 downTo 0 step 2){
println(i)
}
# ์ฆ๊ฐ ๋ฒ์๋ .. ์ฐ์ฐ์๋ฅผ ์ด์ฉํ๋ค. ๊ฐ์๋ฒ์๋ downToํค์๋๋ฅผ ์ฌ์ฉํ๊ณ , step ํค์๋๋ก ์ฆ๊ฐ์ ๊ฐ๊ฒฉ์ ์กฐ์ ํ๋ค.
while
//while
var x = 10
println(x)
while (x > 0){
x--
println(x)
}
//do while
var x = 10
do{
x--
println(x)
}while(x > 0)
๊ฒฐ๊ณผ
9
8
7
6
5
4
3
2
1
0
'๊ฐ๋ฐ ํ์์บก์ > Kotlin' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Kotlin] ์ธํฐํ์ด์ค (0) | 2020.08.27 |
---|---|
[Kotlin] ํด๋์ค (0) | 2020.08.27 |
[Kotlin] ๊ธฐ๋ณธ ์๋ฃํ๊ณผ ๋ฐฐ์ด (0) | 2020.08.25 |
[Kotlin] ํจ์(function) (0) | 2020.08.25 |
[Kotlin] val / var ์ฐจ์ด์ (0) | 2020.08.04 |