안녕하세요
이번 포스팅은 Kotlin 제어 흐름에 대해 포스팅하겠습니다.
제어 흐름은 조건에 따라 실행되는 구문을 구분한 것입니다.
a가 5이고, b가 10일 때를 가정해보죠
if( a > b ) {
println("a가 b보다 크다")
} else {
println("a가 b보다 작다")
}
이렇게 되었을 때 else 구문에 있는 "a가 b보다 작다"가 출력됩니다.
if ~ else보다 더 세부적으로 경우를 나누는 else if 도 있습니다
if( a > b) {
println("a가 b보다 크다")
} else if( a < b) {
println("a가 b보다 작다")
} else if(a == b) {
println("a와 b는 같다")
} else {
}
값을 리턴하는 if문도 있습니다.
이렇게 사용하는 경우는 저도 처음봤네요 ㅎㅎ
val max = if( a > b ) a else b
전체 코드로 한번 보겠습니다.
package com.example.myapplication.Kotlin
// 08. 제어 흐름
// - if, else
fun main(args: Array<String>) {
val a : Int = 5
val b : Int = 10
// if/ else 사용하는 방법 (1)
if(a > b) {
println("a가 b보다 크다")
} else {
println("a가 b보다 작다")
}
// if / else 사용하는 방법 (2)
if(a > b) {
println("a가 b보다 크다")
}
// if/ else if/ else 사용하는 방법
if( a > b) {
println("a가 b보다 크다")
} else if( a < b) {
println("a가 b보다 작다")
} else if(a == b) {
println("a와 b는 같다")
} else {
}
// 값을 리턴하는 if 사용 방법
val max = if( a> b) {
a // 5
} else {
b // 10
}
val max2 = if(a > b) a else b
println()
println(max)
println(max2)
}
변수에 null 이 있을 때, null을 처리해주는 방식이 있습니다.
바로 엘비스 연산자인데요
엘비스 연산자는 "?:" 형태로 사용하며 null을 처리할 수 있게 해줍니다.
val number : Int? = null
val number2 = number ?: 10
println(number2)
위와 같은 경우, number가 null이기 때문에 10 을 대신 number2에 넣어줍니다.
number가 null이 아닌 경우에는 정상적으로 number가 number2에 값이 들어가겠죠.
다음은 전체 코드 입니다.
package com.example.myapplication.Kotlin
fun main(args: Array<String>) {
val a : Int? = null
val b : Int = 10
val c : Int = 100
if(a == null) {
println("a is null")
} else {
println("a is not null")
}
if(b + c == 110) {
println("b plus c is 110")
} else {
println("b plus c is not 110")
}
// 엘비스 연산자 >> ?: null 인 경우 null을 처리할 수 있게 해줌
val number : Int? = 100
val number2 = number ?: 10
println()
println(number2)
val num1 : Int = 10
val num2 : Int = 20
val max = if( num1> num2) {
num1 // 5
} else if( num1 == num2) {
num2 // 10
} else {
100
}
}
'모바일 > Kotlin' 카테고리의 다른 글
[Kotlin] 코틀린 배열 (0) | 2021.03.30 |
---|---|
[Kotlin] 코틀린 제어흐름(2) - when 구문 (0) | 2021.03.30 |
[Kotlin] 코틀린 연산자 (0) | 2021.03.28 |
[Kotlin] 코틀린 메서드(함수) (0) | 2021.03.28 |
[Kotlin] 코틀린이란?, 코틀린의 변수와 자료형 (0) | 2021.03.11 |
댓글