Skip to content

基本型

Kotlinのすべての変数とデータ構造には型があります。型は、その変数やデータ構造に対して何ができるか、言い換えれば、どのような関数やプロパティを持っているかをコンパイラに伝えるため、重要です。

前章の例では、KotlinはcustomersInt型であることを認識できました。 Kotlinが型を推論する能力は型推論と呼ばれます。customersには整数値が割り当てられています。ここから、Kotlinはcustomersが数値型Intであると推論します。その結果、コンパイラはcustomersに対して算術演算を実行できることを認識します。

kotlin
fun main() {
    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
}

TIP

+=-=*=/=%= は複合代入演算子です。詳細については、複合代入を参照してください。

Kotlinには、以下の基本型があります。

カテゴリ基本型コード例
整数ByteShortIntLongval year: Int = 2020
符号なし整数UByteUShortUIntULongval score: UInt = 100u
浮動小数点数FloatDoubleval currentTemp: Float = 24.5fval price: Double = 19.99
論理値Booleanval isEnabled: Boolean = true
文字Charval separator: Char = ','
文字列Stringval message: String = "Hello, world!"

基本型とそのプロパティの詳細については、基本型を参照してください。

この知識があれば、変数を宣言し、後で初期化することができます。Kotlinは、変数が最初の読み取りの前に初期化される限り、これを管理できます。

初期化せずに変数を宣言するには、: を使用して型を指定します。例えば、

kotlin
fun main() {
    // 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
}

変数が読み取られる前に初期化しない場合、エラーが表示されます。

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

基本型の宣言方法がわかったところで、次はコレクションについて学びましょう。

演習

演習

各変数に正しい型を明示的に宣言してください:

|---|---|

kotlin
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 = '
'
}

|---|---|

kotlin
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 = '
'
}

次のステップ

コレクション