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>
.
2. 함수 선언
fun first(): Unit {
println("Hello World!")
}
fun second(name: String) {
println("Hello $name")
}
fun third(a: Int, b: Int): Int {
return a + b
}
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와 유사한 기능을 하는 대신 좀 더 간결하고 직접적으로 표현이 가능합니다.
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
'Android > Kotlin' 카테고리의 다른 글
kotlin Extension 으로 핸드폰 크기 확인 (0) | 2019.05.22 |
---|---|
extesion 이용한 custom toast 만들기 (0) | 2018.11.28 |
Material Calendar 커스텀하기 (2) (12) | 2018.11.28 |
kotlin 으로 recyclerView 구성하기 (0) | 2018.05.14 |
기본 fun 만들기 (0) | 2018.05.12 |