< Dev-Kidult />

Java to Kotlin - 2. 조건문과 반복문 본문

개발/Back-end

Java to Kotlin - 2. 조건문과 반복문

개른이 2022. 12. 28. 16:15

조건문

if

if문은 자바와 코틀린이 크게 다른게 없다. 그럼에도 분명 차이점은 분명 존재한다.

var a = 5;
var b = a > 5 ? "aaa" : "bbb";
자바에서는 삼항연산자를 지원한다.

하지만 코틀린에서는 삼항연산자를 지원하지 않는다.

코틀린은 함수형 언어이며, 조건문도 하나의 식(expression)이기에 해당 식을 변수에 지정 할 수 있기 때문이다.

var a = 5
var b = if (a > 5) "aaa" else "bbb"

 

switch & when

자바는 switch case, 코틀린은 when을 쓴다. 최대한 비교가능하게 자바는 17버전 기준으로 시작하자.

// normal case
var month = 12;
switch (month) {
  case 3,4,5 -> System.out.println("봄");
  case 6,7,8 -> System.out.println("여름");
  case 9,10,11 -> System.out.println("가을");
  case 12,1,2 -> System.out.println("겨울");
  default -> throw new IllegalArgumentException();
}

//enum case
var season = Season.WINTER;
switch (season) {
  case SPRING -> System.out.println("봄");
  case SUMMER -> System.out.println("여름");
  case FALL -> System.out.println("가을");
  case WINTER -> System.out.println("겨울");
}

//pattern matching
var a = new Object();
result switch (a) {
  case String s -> "it`s string";
  case Integer i -> "it`s integer";
  default -> "unknown data type";
};
val month = 12
when (month) {
  3, 4, 5 -> println("봄")
  in 6..10 -> println("여름")
  in 9 until 12 -> println("가을")
  12, 1, 2 -> println("겨울")
  else -> throw IllegalArgumentException()
}

val season = Season.WINTER
when {
  season == Season.SPRING -> println("봄")
  season == Season.SUMMER -> println("여름")
  season == Season.FALL -> println("가을")
  season == Season.WINTER -> println("겨울")
}

val a = Any()
val b = when (a) {
  in "a".."z" -> "it`s spelling"
  is String -> "it`s string"
  is Int -> "it`s Int"
  else -> "it`s any"
}

fun twoAndThree(func: (Int, Int) -> Int) = func(2, 3)
when (twoAndThree { i, i2 -> i + i2 }) {
  ...
}

 

일단 자바의 경우에는 인자로 변수 만을 받을 수 있고, 해당 조건문을 리턴하거나 혹은 로직수행하는정도에서 그치는 반면

코틀린의 경우에는 인자로 변수를 받거나 안받을수도 있고, 심지어 함수를 받는 함수를 넣을 수도 있다.

조건 절 또한 상당히 자유로운 편인데 “in” 키워드로 범위를 지정할 수도 있고 is로 타입을 체크할 수도 있다.

그리고 when 또한 if문과 마찬가지로 해당 절을 변수에 지정 할 수도 있다.

 

반복문

for

var array = new int[] { 1, 2, 3, 4, 5 };

for (var i = 0; i < array.length; i++) {
  System.out.println(array[i]);
}

for (var i : array) {
  System.out.println(i);
}

자바에서는 일반for문과 향상된 for문 외에는 for문을 활용한 문법이 따로 없다.

val array = arrayOf(1, 2, 3, 4, 5)
for (i in 0 until array.size) {
  println(array[i])
}

for (i in array) {
  println(i)
}

for ((index, value) in array.withIndex()) {
  println("index: $index, value: $value")
}

val range = 0 until 10 //eq = 0.until(10) -> infix func
for (i in range) {
  //...
}

val progression = 10 downTo 0 step 2  // eq = 10.downTo(0).step(2)
for (i in progression) {
  //...
}

array.forEach { println(it) }
array.forEachIndexed { index, value -> println("index: $index, value: $value") }

코틀린에서는 위와 같이 쓴다.

기본적으로 i(변수지정)을 하고 “in” 키워드로 for문을 돌릴 대상을 지정한다.

여기에는 array, list, set등 + range, progression을 받아서 처리 할 수 있다.

 

return to labels

fun foo() {
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return // non-local return directly to the caller of foo()
        print(it)
    }
    println("this point is unreachable")
}
// 12

fun foo() {
    listOf(1, 2, 3, 4, 5).forEach lit@{
        if (it == 3) return@lit // local return to the caller of the lambda - the forEach loop
        print(it)
    }
    print(" done with explicit label")
}
// 1245 done with explicit label

fun foo() {
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return@forEach // local return to the caller of the lambda - the forEach loop
        print(it)
    }
    print(" done with implicit label")
}
// 1245 done with implicit label

fun foo() {
    listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) {
        if (value == 3) return  // local return to the caller of the anonymous function - the forEach loop
        print(value)
    })
    print(" done with anonymous function")
}
// 1245 done with anonymous function

fun foo() {
    run loop@{
        listOf(1, 2, 3, 4, 5).forEach {
            if (it == 3) return@loop // non-local return from the lambda passed to run
            print(it)
        }
    }
    print(" done with nested loop")
}
// 12 done with nested loop

 

각종 forEach 상황에서의 return 이다. 제일 쉽게 생각하려면 네이밍라벨이 없다면 제일가까운 함수로 리턴한다고 생각하면 된다.

반응형
Comments