기본 타입

기본 타입 (Basic types)

Kotlin의 모든 변수와 자료구조는 타입을 가져요. 타입은 그 변수나 자료구조로 무엇을 할 수 있는지, 즉 어떤 함수와 프로퍼티를 갖고 있는지를 컴파일러에게 알려 주기 때문에 중요해요.

출처: Kotlin 공식 문서

본문

지난 장에서 Kotlin이 앞선 예시의 customersInt 타입이라는 걸 알아냈죠. Kotlin이 타입을 추론하는 능력을 타입 추론(type inference)이라고 해요. customers에는 정수 값이 할당돼요. 여기서 Kotlin은 customers가 숫자 타입인 Int라고 추론해요. 그 결과 컴파일러는 customers로 산술 연산을 수행할 수 있다는 걸 알게 돼요:

fun main() {
//sampleStart
    var customers = 10

    // Some customers leave the queue
    customers = 8

    customers = customers + 3 // Example of addition: 11
    customers += 7            // Example of addition: 18
    customers -= 3            // Example of subtraction: 15
    customers *= 2            // Example of multiplication: 30
    customers /= 3            // Example of division: 10

    println(customers) // 10
//sampleEnd
}

Tip: +=, -=, *=, /=, %=는 복합 대입 연산자(augmented assignment operator)예요. 자세한 내용은 Augmented assignments 문서를 참고하세요.

Kotlin이 제공하는 기본 타입은 전체적으로 이렇게 돼요:

카테고리 기본 타입 예시 코드
정수 (Integers) Byte, Short, Int, Long val year: Int = 2020
val amount: Long = 350_000_000
부호 없는 정수 (Unsigned integers) UByte, UShort, UInt, ULong val score: UInt = 100u
부동소수점 수 (Floating-point numbers) Float, Double val currentTemp: Float = 24.5f
val price: Double = 19.99
불리언 (Booleans) Boolean val isEnabled: Boolean = true
문자 (Characters) Char val separator: Char = ','
문자열 (Strings) String val message: String = "Hello, world!"

기본 타입과 그 프로퍼티에 대한 자세한 내용은 Types overview 문서를 참고하세요.

이 지식을 바탕으로 변수를 선언하고 나중에 초기화할 수 있어요. Kotlin은 변수가 처음 읽히기 전에 초기화되기만 하면 이를 관리해 줘요.

초기화 없이 변수를 선언하려면 :로 타입을 지정해요. 예를 들어:

fun main() {
//sampleStart
    // Variable declared without initialization
    val d: Int
    // Variable initialized
    d = 3

    // Variable explicitly typed and initialized
    val e: String = "hello"

    // Variables can be read because they have been initialized
    println(d) // 3
    println(e) // hello
//sampleEnd
}

변수를 읽기 전에 초기화하지 않으면 오류가 발생해요:

fun main() {
//sampleStart
    // Variable declared without initialization
    val d: Int
    
    // Triggers an error
    println(d)
    // Variable 'd' must be initialized
//sampleEnd
}

이제 기본 타입을 선언하는 방법을 알았으니, 컬렉션을 배워 볼 차례예요.

연습 (Practice)

연습 문제 (Exercise)

각 변수의 올바른 타입을 명시적으로 선언하세요:

fun main() {
    val a: Int = 1000 
    val b = "log message"
    val c = 3.14
    val d = 100_000_000_000_000
    val e = false
    val f = '\n'
}
fun main() {
    val a: Int = 1000
    val b: String = "log message"
    val c: Double = 3.14
    val d: Long = 100_000_000_000_000
    val e: Boolean = false
    val f: Char = '\n'
}