๐Ÿ”ฅTIL๐Ÿ”ฅ์ŠคํŒŒ๋ฅดํƒ€ | Kotlin ๋ฌธ๋ฒ•

hyihyiยท2023๋…„ 11์›” 28์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
7/70
post-thumbnail

์กฐ๊ฑด์‹

when์ ˆ

case๊ฐ€ 1๊ฐœ์ผ ๊ฒฝ์šฐ๋Š” if else, 2๊ฐœ ์ด์ƒ์ผ ๊ฒฝ์šฐ์—๋Š” when์ ˆ์„ ์“ฐ์ž

val x: Int = readLine()

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}

์ฝ”ํ‹€๋ฆฐ์—์„œ when์ ˆ์„ ์‚ฌ์šฉํ•  ๋•Œ nullable์ด๊ณ  ๋ชจ๋“  ์ผ€์ด์Šค๋ฅผ ์ปค๋ฒ„ํ•  ์ˆ˜ ์—†์œผ๋ฉด else๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

์•„๋ž˜์˜ ๊ฒฝ์šฐ๋Š” ๋ชจ๋“  ๋ถ„๊ธฐ๊ฐ€ ์ปค๋ฒ„ ๊ฐ€๋Šฅํ•˜๊ธฐ ๋•Œ๋ฌธ์— else๊ฐ€ ์—†์–ด๋„ ๋œ๋‹ค.

enum class Bit {
    ZERO, ONE
}

val numericValue = when (getRandomBit()) {
    Bit.ZERO -> 0
    Bit.ONE -> 1
    // 'else' is not required because all cases are covered
}
  • else if๊ฐ€ ๋งŽ์•„์งˆ๋•Œ๋Š” when์„ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ๋”์šฑ ๊ฐ€๋…์„ฑ์ด ์ข‹์Œ

๋ฐ˜๋ณต๋ฌธ

for๋ฌธ

  • in (1..10์ผ ๋•Œ 1๊ณผ 10์„ ๋‘˜ ๋‹ค ํฌํ•จ)
for(์š”์†Œ in ๋ฆฌ์ŠคํŠธ) {
	  ์†Œ์Šค์ฝ”๋“œ (๋กœ์ง)
}
// 1๋ถ€ํ„ฐ 5๊นŒ์ง€ ๋ณ€ํ™”ํ•˜๋Š” i๋ณ€์ˆ˜
for(i in 1..5) {
	 println("${i}๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ")
}
1๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
2๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
3๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
4๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
5๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
  • until
for(์ธ๋ฑ์Šค in ์‹œ์ž‘๊ฐ’ until ๋งˆ์ง€๋ง‰๊ฐ’) {
		์†Œ์Šค์ฝ”๋“œ (๋กœ์ง)
}
// 1๋ถ€ํ„ฐ 4๊นŒ์ง€ ๋ณ€ํ™”ํ•˜๋Š” i๋ณ€์ˆ˜
for(i in 1 until 5) {
	 println("${i}๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ")
}
1๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
2๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
3๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
4๋ฒˆ์งธ: ๋‚ด ์ด๋ฆ„์€ ์ฐธ์ƒˆ
  • break : ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘˜๋Ÿฌ์‹ผ ๋ฃจํ”„๋ฅผ ์ข…๋ฃŒ
  • continue : ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๋‘˜๋Ÿฌ์‹ผ ๋ฃจํ”„์˜ ๋‹ค์Œ ๋ฐ˜๋ณต์„ ์ง„ํ–‰
var infos = arrayOf("๊ฟฉ", "๋‹ญ", "์ฐธ์ƒˆ", "์˜ค๋ชฉ๋ˆˆ์ด", "๊ณต์ž‘์ƒˆ")

for(info in infos) {

  if(info == "์ฐธ์ƒˆ") {
      println("์ฐพ์•˜๋‹ค ์ฐธ์ƒˆ!")
      break // for๋ฌธ์„ ํƒˆ์ถœ
  } else {
      continue //for๋ฌธ์˜ ๋‹ค์Œ ๋ฐ˜๋ณต์„ ์ง„ํ–‰
  }
  
}
profile
๋‚ด๊ฐ€ ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๊ฒŒ ์“ฐ๋Š” ๋ธ”๋กœ๊ทธ

0๊ฐœ์˜ ๋Œ“๊ธ€