기본 타입
숫자
- Byte : 8-bits
- Short : 16-bits
- Int : 32-bits
- Long : 64-bits
- Float : 32-bits
- Double : 64-bits
문자
- Char
불린
- Boolean : true, false
배열
- Array : Array class
- ByteArray
- ShortArray
- IntArray
문자열
- String
func func() {
var a = 'AAA';
return a;
}
상수와 변수
- val : 상수
- var : 변수
val a = 1
var b = 2
b = 3
선언법
var a: Int = 5
lateinit var b:Int
nullable 변수
var a: Int?
정수값을 가지던지, null 일 수 있다.
Package
package org.example
기본적으로 import 되는 패키지들
- kotlin.*
- kotlin.annotation.*
- kotlin.collections.*
- kotlin.comparisons.* (since 1.1)
- kotlin.io.*
- kotlin.ranges.*
- kotlin.sequences.*
- kotlin.text.*
import
import org.example.Message
import org.example.*
import org.test.Message as testMessage // testMessage stands for 'org.test.Message'
흐름제어
if
// Traditional usage
var max = a
if (a < b) max = b
// With else
var max: Int
if (a > b) {
max = a
} else {
max = b
}
// As expression
val max = if (a > b) a else b
val max = if (a > b) {
print("Choose a")
a
} else {
print("Choose b")
b
}
when
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> { // Note the block
print("x is neither 1 nor 2")
}
}
range 로 체크가능
when (x) {
in 1..10 -> print("x is in the range")
in validNumbers -> print("x is valid")
!in 10..20 -> print("x is outside the range")
else -> print("none of the above")
}
For Loops
for (item in collection) print(item)
for (item: Int in ints) {
// ...
}
for (i in 1..3) {
println(i)
}
for (i in 6 downTo 0 step 2) {
println(i)
}
for (i in array.indices) {
println(array[i])
}
for ((index, value) in array.withIndex()) {
println("the element at $index is $value")
}
While Loops
while (x > 0) {
x--
}
do {
val y = retrieveData()
} while (y != null) // y is visible here!
Functions
fun double(x: Int): Int {
return 2 * x
}
fun read(
b: Array<Byte>,
off: Int = 0,
len: Int = b.size,
) { /*...*/ }
fun foo(
bar: Int = 0,
baz: Int,
) { /*...*/ }
foo(baz = 1) // The default value bar = 0 is used
Collections
List
val list: List<Int> = List(5, {i -> i})
//
val list: List<Int> = listOf(1,2,3,4,5)
immutable 하며, [] 로 접근가능
MutableList
val array1 = MutableList<Int>(5, {i -> i})
array[0] = 10
val array2 = mutableListOf(1,2,3)
array2.add(4)
Set
중복을 허용하지 않음
val set1: Set<Int> = setOf<Int>(3,3,1,2)
3이 중복되게 선언이 되어도 set1에는 3이 하나만 들어간다.
Map
키-밸류 형태
val map1: Map<String, Int> = mapOf("One" to 1, "Two" to 2, "Three" to 3)
val map2: Map<String, Int> = mapOf(Pair("Four", 4), Pair("Five", 5))
Coroutines
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
GlobalScope.launch{ ... }
는 thread { .. }
또는 delay(...)
with Thread.sleep(...)
으로 대체가능
delay
는 suspending function으로 코루틴을 블락한다. 즉, 코루틴 안에서 사용되어야한다. 쓰레드 안에서는 에러 발생.
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L)
println("World!")
}
println("Hello,") // main thread continues here immediately
runBlocking { // but this expression blocks the main thread
delay(2000L) // ... while we delay for 2 seconds to keep JVM alive
}
}
Date()
val cal = Calendar.getInstance() cal.time = Date() val df: DateFormat = SimpleDateFormat(“yyyy-MM-dd”)
cal.add(Calendar.Month, 1)
범위 지정함수
apply, run, with, let, also
data class Person ( var name: String = “”, var age: Int = 0, var temperature: Float = 36.5f )
apply
수신객체 내부 프로퍼티를 변경한 다음 수신객체 자체를 반환하고자 할 때
var p = Person().apply { name = “new name” age = 29 temperature = 36.4f }
run
apply 와 유사, 수신객체를 리턴하지않고, run 블록의 마지막 라인을 return 한다.
data class Person ( var name: String = “”, var age: Int = 0, var temperature: Float = 36.5f ) { fun isSick(): Boolean = temperature > 37.5f }
val person = Person(name = “FB”, age = 29, temperature = 36.5f) val isPersonSick = person.run { temperature = 37.2f isSick() // 이 부분이 return }
with
run 과 동일, run은 확장함수로 사용되지만 with는 수신객체를 인자로 받아 사용하는 차이 (run 사용하는 것이 낫다.) val person = Person(name = “FB”, age = 29, temperature = 36.5f) val isPersonSick = with(person) { temperature = 37.2f isSick() // 이 부분이 return }
let
수신객체 이용한 후 마지막 줄이 return 된다. run, with와 달리 수신객체를 it 으로 접근해야한다. null check 후 코드를 실행해야할 때, nullable한 수신객체를 다른 타입의 변수로 변환해야하는 경우 사용 nullable 한 수신객체를 다룰 때는 let을 사용해야한다.
var person: Person? = null val isReserved = person?.let { it: Person -> reserveMovie(it) }
also
apply 처럼 수신객체를 return한다. 프로퍼티를 세팅하는 것 외에 다른 작업도 가능 it 으로 객체 접근, 잘 사용안됨
var number = 3
fun getAndIncrease() = number.also { number++ }
getAndIncrease() getAndIncrease()
// 3 // 4