-
kotlin) 코틀린에서 코드를 제어하는 방법kotlin 2024. 7. 2. 22:03
코틀린에서 조건문을 다루는 방법
1. if 문
문법 자체는 Java 와 큰 차이점이 없다.
fun validateScoreIsNOtNegative(score : Int){ if( score < 0 ){ throw IllegalArgumentException("$score} 는 0보다 작을 수 없다.") } }
하지만 내부적으로 차이점이 있다
- Java : Statement
- Statement : 프로그램의 문자, 하나의 값으로 도출되지 않는다
- Kotlin : Expression
- Expression : 하나의 값으로 도출되는 문장
//Java String grade = if (score >= 50){ //Java 는 if문을 하나의 값으로 취급하지 않으니 해당 코드는 불가능하다 "P"; } else { "F"; } String grade = score >= 50 ? "P" : "F" //3항 연산자를 사용해야 가능하다 //Kotlin val grade = if(score>=50){ "P" } else { "F" }
2. Expression 과 Statement
//java if(0 <= score && score <= 100){ } //kotlin if(score in 0...100){ }
3. switch 와 when
fun getGradeWithSwitch(score : Int):String{ return when(score/10){ in 90..99 -> "A" //.. 문 사용 가능 8 -> "B" 7 -> "C" else -> "D" } } fun startsWithA(obj: Any): Boolean{ return when (obj){ is String -> obj.startsWith("A") //형변환 및 결과값 처리 가능 else -> false } } fun judgeNumber(number: Int){ when (number){ 1, 0, -1 -> println("어디서 많이 본 숫자입니다") else -> println("1, 0, -1 이 아닙니다") } } fun judgeNumber2(number: Int){ when { number == 0 -> println("주어진 숫자는 0입니다") number % 2 == 0 -> println("주어진 숫자는 짝수입니다") else -> println("주어지는 숫자는 홀수입니다") } }
코틀린에서 반복문을 다루는 방법
1. for-each 문
//Java List<Long> numbers = Arrays.asList(1L,2L,3L); for(long number : numbers){ System.out.println(number); } //kotlin val numbers = listOf(1L, 2L, 3L) for(number in numbers){ // : 대신 in 을 쓴다. 그리고 앞에 Type 을 작성하지 않는다 println(number) }
2. 전통적인 for 문
//올라가는 숫자일 경우 //Java for (int i = 1; i <=3; i ++) { System.out.println(i); } //Kotlin for(i in 1..3){ println(i) } //내려가는 숫자일 경우 //Java for (int i = 3; i >= 1; i--){ System.out.println(i); } //Kotlin for (i in 3 downTo 1) { //downTo 를 통해 1씩 빼준다는 의미 println(i) } //두칸씩 올리는 경우 //Java for (int i = 1; i <= 5; i += 2) { System.out.println(i); } //Kotlin for(i in 1..5 step 2){ //step 을 통해서 2씩 더해준다는 의미 println(i) }
3. Progression 과 Range
- .. 연산자 : 범위를 만들어 내는 연산자
- 1..3 : 1부터 3의 범위
- IntRange 라는 클래스가 있고 IntProgression 를 상속받고있음
- IntProgression : 등차수열을 만들고있는 함수
- Kotlin 에서 전통적인 for 문은 등차수열을 사용한다.
4. while 문
Java 와 동일함
코틀린에서 예외를 다루는 방법
1. try catch finally 구문
//Java private int parseIntOrThrow(@NotNull String str){ try{ return Integer.parseInt(str); } catch (NumberFormatException e){ throw new IllegalAccessException(String.format("주어진 %s는 숫자가 아닙니다",str)); } } //Kotlin fun parseIntOrThrow(str: String): Int{ try { return str.toInt() } catch (e: NumberFormatException) { //타입이 뒤에 위치 throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다") //new 를 사용하지 않음 } } // if 와 동일하게 return 가능 fun parseIntOrThrow(str: String): Int?{ return try { str.toInt() } catch (e: NumberFormatException) { //타입이 뒤에 위치 throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다") //new 를 사용하지 않음 } }
2. Checked Exception 과 Unchecked Exception
Kotlin 에서는 Cehcked Exception 과 Unchecked Exception 을 구분하지 않는다
-> 모두 Unchecked Exception 입니다
3. try with resources
//Java public void readFile(String path) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(path))) { System.out.println(reader.readLine()); } } fun readFile(path: String) { //throws 가 붙지 않는다. BufferedReader(FileReader(path)).use { reader -> //use 를 통해 try with resource 를 대신한다 println(reader.readLine()) } }
코틀린에서 함수를 다루는 방법
1. 함수 선언 문법
//Java public int max(int a, int b){ if(a > b){ return a; } else { return b; } } //Kotlin fun max(a: Int, b: Int): Int { return if(a > b) { a } else { b } } // {} 대신 = 로 변환 fun max(a: Int, b: Int) = // =으로 하면 a,b 의 Type 을 추론할 수 있다 if (a > b) { a } else { b } fun max(a: Int, b: Int) : Int = if (a > b) a else b //한줄로도 변경 가능
- 함수는 클래스 안에 있을수도 있고
- 파일 최상단에 있을 수도 있고
- 한 파일 안에 여러 함수들이 있을 수도 있습니다.
2. default parameter
fun main() { repeat("Hello World") } fun repeat(str: String, num: Int = 3, useNewLine: Boolean = true) { //default 값을 넣을 수 있다. for(i in 1..num){ if(useNewLine){ println(str) } else { println(false) } } }
3. named argument (parameter)
fun main() { repeat("Hello World") //default 값 그대로 사용 repeat("Hellow World", useNewLine = false) //특정 parameter 만 설정 } fun repeat(str: String, num: Int = 3, useNewLine: Boolean = true) { //default 값을 넣을 수 있다. for(i in 1..num){ if(useNewLine){ println(str) } else { println(false) } } }
- 기능의 장점
- builder 를 생성하지 않아도 builder 의 기능을 사용할 수 있다.
4. 같은 타입의 여러 파라미터 받기 (가변인자)
//Java public static void printAll(String... strings) { for (String str : strings) { System.out.println(str); } } //Kotlin fun main() { printAll("A","B","C") var array = arrayOf("A","B","C") printAll(*array) // spread 연산자 : 배열 안에 있는것들을 마치 ,를 쓰는것처럼 꺼내준다 } fun printAll(vararg strings: String){ for(str in strings){ println(str) } }
'kotlin' 카테고리의 다른 글
kotlin) Kotlin 의 지연과 위임 (0) 2024.07.18 kotlin) 추가적으로 알아두어야 할 코틀린 특성 (0) 2024.07.13 kotlin) 코틀린에서의 FP (0) 2024.07.09 kotlin) 코틀린에서의 OOP (0) 2024.07.06 kotlin) 코틀린에서 변수와 타입, 연산자를 다루는 방법 (0) 2024.07.04 - Java : Statement