[Kotlin] 베이직 기초 문법 (2)

반응형

이전 포스팅에 이어서 간단한 코틀린 문법을 전반적으로 알아보겠습니다. 코틀린은 현대적인 언어의 대부분의 장점을 가지고 있습니다. 그중에 타입추론과 타입체크가 편리하고 Nullable 을 도입함으로써 어플리케이션의 개발시 안정성이 높아졌습니다. 이번 포스팅에서는 코틀린이 가진 간단한 특징을 볼 수 있습니다. When 과 같은 구문은 스위치와 비슷하지만 훨씬 편리하고 다양하게 활용할 수 있어서 좋습니다. 기존의 자바보다 문자열 템플릿 또한 간결하고 활용범위가 넓습니다.

 

주석

 코틀린은 한 줄 주석과 블록 형태의 여러행 주석을 지원합니다.

// This is an end-of-line comment
/* This is a block comment
on multiple lines. */

 

 블록 주석의 경우 안쪽에 또다른 주석을 넣을 수 있습니다.

/* The comment starts here
/* contains a nested comment *⁠/
and ends here. */

 

문자열 템플릿

 문자열 안에서 ${} 구문을 통해 변수 또는 함수등을 사용할 수 있습니다.

var a = 1
// simple name in template:
val s1 = "a is $a"
a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"

 

조건문

 대부분의 언어처럼 다음과 같이 if ~ else 구문으로 표현합니다.

fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}

 

 위의 구문을 다음과 같이 표현할 수도 있습니다.

fun maxOf(a: Int, b: Int) = if (a > b) a else b

 

for 루프

 다음과 같은 구문으로 컬렉션 요소를 순환할 수 있습니다.

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}

 

 index 값이 필요하다면 다음과 같이 index 값을 가져올 수도 있습니다.

val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}

 

while 루프

 for 구문외에 while을 동해 값을 순환할 수도 있습니다.

val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}

 

when 표현식

 다른 언어의 switch와 비슷합니다. else 의 경우 switch 구문의 default와 동일한 기능을 합니다.

fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}

 

Ranges

 Range를 이용하면 해당하는 값이 범위를 벗어났는지 확인할 수 있습니다.

val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}

 

 다음과 같이 배열의 길이 대해서도 미리 체크할 수 있습니다.

val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex) {
println("-1 is out of range")
}
if (list.size !in list.indices) {
println("list size is out of valid list indices range, too")
}

 

 특정한 리터럴 값을 생성할 때도 Range 구문을 쓸 수 있습니다.

for (x in 1..5) {
print(x)
}

 

 만약 특정한 범위 내에서 일정한 값을 만들고 싶다면 downTo 또는 step을 이용해서 만들수 있습니다.

for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}

 

컬렉션

 다음과 같이 컬렉션에 대해서 순환할 수 있습니다.

for (item in items) {
println(item)
}

 

 when 구문에서 컬렉션의 요소들을 확인할 수 있습니다.

when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}

 

 컬렉션에 대하여 다음 처럼 filter나 map 같은 고차함수를 활용할 수 있습니다.

val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }

 

Nullable 

코틀린은 Nullable 형태의 데이터 타입을 가지고 있습니다. 다음 함수는 null 을 반환하거나 String을 반환할 수 있습니다. 

fun parseInt(str: String): Int? {
// ...
}

 

 문자열을 Int 형태로 형변환 할 경우 실패할 가능성이 있는데 그때는 Nullable 타입이 되버립니다. 때문에 다음과 같이 값이 null 인지 확인을 해줍니다.

fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// Using `x * y` yields error because they may hold nulls.
if (x != null && y != null) {
// x and y are automatically cast to non-nullable after null check
println(x * y)
}
else {
println("'$arg1' or '$arg2' is not a number")
}
}

 

다음과 같이 확인할 수도 있습니다.

// ...
if (x == null) {
println("Wrong number format in arg1: '$arg1'")
return
}
if (y == null) {
println("Wrong number format in arg2: '$arg2'")
return
}
// x and y are automatically cast to non-nullable after null check
println(x * y)

 

타입체크와 타입캐스팅

 is 명령을 통해 해당 인스턴스의 타입을 알 수 있습니다.  

fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}
// `obj` is still of type `Any` outside of the type-checked branch
return null
}

 

다음과 같이 확인할 수도 있습니다.

fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}

 

다음과 같이 확인할 수도 있습니다.

fun getStringLength(obj: Any): Int? {
// `obj` is automatically cast to `String` on the right-hand side of `&&`
if (obj is String && obj.length > 0) {
return obj.length
}
return null
}

 

 

 

반응형

'언어 > 코틀린' 카테고리의 다른 글

[Kotlin] 베이직 기초 문법 (1)  (0) 2021.12.21

댓글

Designed by JB FACTORY