본문 바로가기

Android/Kotlin

kotlin 사용 이유와 기본 문법

반응형

2017년 공식 채택된 "코틀린", 코틀린을 사용하는 이유는 

1. 간결하다! -> 문법이 자바에 비해 너무나도 짧고 편하게 사용할 수 있다.

2. 안정성이 높다 -> 간단한 처리로 안정성이 높아진다.


등이 있지만, 위의 2가지가 크게 대두된다고 생각합니다.




잡담은 생략하고...


1. 변수 선언 시 val 와 var 의 차이는 무엇일까요?



val : 값을 할당하고 나면 그 후에 변경할 수 없는 변수이며, java에서 final을 붙인 변수와 동일

var : 값을 할당하고 나면 그 후에 자유자재로 변경할 수 있는 변수이며, java에서 final을 붙이지 않은 변수와 동일



합니다. 즉,


final String name="OhNo";    는

val name: String = "OhNo"    와 같습니다.( ";"을 코틀린에서는 붙이지 않습니다. 한줄한줄 줄로써 인식합니다.)



변수의 가변/불변과 마찬가지로 컬렉션 자료형(List..) 에서도 가변/불변을 구분하는데,


val numbers:MutableList<Int> = mutableListOf(1, 2, 3)
val readOnly:List<Int> = numbers
println(numbers) // [1, 2, 3]
numbers.add(4)
println(readOnly) // [1, 2, 3, 4]
readOnly.add(5) // add 에 빨간 표시로 compile error가 된다.



위처럼 mutableList를 사용해야지만 수정할 수 있습니다.


코틀린 공식 싸이트(참고 : https://kotlinlang.org/docs/reference/collections.html)에서도


The Kotlin List<out T> type is an interface that provides read-only operations like size, get and so on. Like in Java, it inherits from Collection<T> and that in turn inherits from Iterable<T>. Methods that change the list are added by the MutableList<T> interface. This pattern holds also for Set<out T>/MutableSet<T> and Map<K, out V>/MutableMap<K, V>.


이렇게 정의했듯, List로 할당 시 읽을 수만 있으며, MutableList로 할당해야 수정이 가능하다고 합니다.



2. 함수 선언

fun first(): Unit {
println("Hello World!")
}
fun second(name: String) {
println("Hello $name")
}
fun third(a: Int, b: Int): Int {
return a + b
}


함수의 반환값으로 사용한 Unit은 자바의 void와 유사하게 사용됩니다.
first()                             //  Hello World!
second("World!") // Hello World!
println(third(1, 3)) // 4


이런 식으로 사용이 가능합니다.




3. 조건문

fun if_else(a:Int, b:Int) : Int {
if(a>b) return a
else return b
}
fun count(count:Int) {
when(count) {
1->println("There is $count item.")
else -> println("There are $count items")
}
}


println(if_else(2, 3))      // 3
count(1) // There is 1 item.
count(2) // There are 2 items

이렇게 if/else문은 선언하는 것은 같으며, when은 switch와 유사한 기능을 하는 대신 좀 더 간결하고 직접적으로 표현이 가능합니다.




4. 반복문
fun for_each(items:List<String>) {
for(item in items) {
println("item : $item")
}
}
fun _while() {
val items = listOf("Fun", "Var", "Val", "Item")
var i = 0
while (i<items.size) {
println("item : ${items[i]}")
i++
}
}

val items = listOf("Fun", "Var", "Val")
for_each(items) // item : Fun //item : Var //item : Val
_while() // item : Fun //item : Var //item : Val //item : Ite

kotlin에서 while문은 자바와 동일하며, for문은 for-each 문만 지원을 합니다. (java는 for / for-each 둘다 지원)


이상 간단한 문법 사용 방법을 알아봤습니다.

다음에는 java로 구성한 소스를 kotlin으로 변경하는 방법 등에 대해 알아보겠습니다.












반응형