작성완료: 2022-03-02
널리 사용되는 switch
구문 대신, 코틀린은 더 유연하고 클리어한 when
구조를 지원한다. 이것은 구문 또는 표현식으로 사용될 수 있다.
fun main() {
cases("Hello")
cases(1)
cases(0L)
cases(MyClass())
cases("hello")
}
fun cases(obj: Any) {
when (obj) { // 1
1 -> println("One") // 2
"Hello" -> println("Greeting") // 3
is Long -> println("Long") // 4
!is String -> println("Not a string") // 5
else -> println("Unknown") // 6
}
}
class MyClass
when
문이다.obj
가 1
과 같은지 확인한다.obj
가 Hello
와 같은지 확인한다.하나가 만족될 때 까지 모든 브랜치 컨디션이 순차적으로 체크된다는 것에 주의하자. 즉 오직 가장 처음 들어맞는 브랜치만 실행된다.
fun main() {
println(whenAssign("Hello"))
println(whenAssign(3.4))
println(whenAssign(1))
println(whenAssign(MyClass()))
}
fun whenAssign(obj: Any): Any {
val result = when (obj) { // 1
1 -> "one" // 2
"Hello" -> 1 // 3
is Long -> false // 4
else -> 42 // 5
}
return result
}
class MyClass
when
문이다.obj
가 1
과 같을 경우 값을 one
으로 지정한다.obj
가 Hello
와 같을 경우 값을 1
로 지정한다.obj
가 Long
인스턴스일 경우 값을 false
로 지정한다. 42
로 값을 지정한다. when
문과 달리, 디폴트 브랜치는 일반적으로 when
표현식에서는 필수적이다. 컴파일러가 다른 브랜치들이 가능한 모든 케이스를 커버한다고 확인할 수 있는 경우만 예외이다.코틀린은 일반적으로 사용되는 모든 루프를 지원한다: for
, while
, do-while
for
코틀린의 for
은 대부분의 언어와 같은 방식으로 동작한다.
val cakes = listOf("carrot", "cheese", "chocolate")
for (cake in cakes) { // 1
println("Yummy, it's a $cake cake!")
}
while
and do-while
while
과 do-while
구조는 대부분의 언어와 비슷하게 동작한다.
fun eatACake() = println("Eat a Cake")
fun bakeACake() = println("Bake a Cake")
fun main(args: Array<String>) {
var cakesEaten = 0
var cakesBaked = 0
while (cakesEaten < 5) { // 1
eatACake()
cakesEaten ++
}
do { // 2
bakeACake()
cakesBaked++
} while (cakesBaked < cakesEaten)
}
iterator
연산자를 클래스 내부에 구현함으로써 이터레이터를 정의할 수 있다.
class Animal(val name: String)
class Zoo(val animals: List<Animal>) {
operator fun iterator(): Iterator<Animal> { // 1
return animals.iterator() // 2
}
}
fun main() {
val zoo = Zoo(listOf(Animal("zebra"), Animal("lion")))
for (animal in zoo) { // 3
println("Watch out, it's a ${animal.name}")
}
}
iterator
로 명명되어야 하고, operator
제한자/수정자를 가져야 한다. next()
: Animal
hasNext()
: Boolean
이터레이터는 확장 함수로써, 또는 타입에 선언할 수 있다.
코틀린에서 range를 정의하기 위해 사용하는 도구 모음이다. 짧게 살펴보자.
for(i in 0..3) { // 1
print(i)
}
print(" ")
for(i in 0 until 3) { // 2
print(i)
}
print(" ")
for(i in 2..8 step 2) { // 3
print(i)
}
print(" ")
for (i in 3 downTo 0) { // 4
print(i)
}
print(" ")
for(i=0; i<=3; ++i)
와 같다.for(i=0; i<3; ++i)
나 python의 루프와 같다.char range 또한 지원된다:
for (c in 'a'..'d') { // 1
print(c)
}
print(" ")
for (c in 'z' downTo 's' step 2) { // 2
print(c)
}
print(" ")
step
과 downTo
또한 지원한다.범위는 if
문에서도 유용하다.
val x = 2
if (x in 1..5) { // 1
print("x is in range from 1 to 5")
}
println()
if (x !in 6..10) { // 2
print("x is not in range from 6 to 10")
}
!in
은 in
의 반대이다.코틀린은 구조적 비교(structural comparison)에 ==
를 사용햐고 참조적 비교(referential comparison)에 ===
를 사용한다.
더 정확하게는, a == b
는 if (a == null) b == null else a.equals(b)
로 컴파일된다.
val authors = setOf("Shakespeare", "Hemingway", "Twain")
val writers = setOf("Twain", "Shakespeare", "Hemingway")
println(authors == writers) // 1
println(authors === writers) // 2
authors.equals(writers)
를 호출하고 set은 원소 순서를 무시하므로 true
를 반환한다.authors
와 writers
가 별개의 참조이므로 false
를 반환한다.코틀린에는 삼항연산자 condition ? then : else
가 없다. 그 대신 if
가 표현문으로 사용될 수 있다:
fun max(a: Int, b: Int) = if (a > b) a else b // 1
println(max(99, -42))