Help us understand the problem. What is going on with this article?

Kotlinの変数宣言

Kotlinでの変数宣言を超ざっくりまとめてみました。

Main.kt
fun main() {
    // var 変数名: 型 = リテラル の形が基本的な形
    var a: Int = 1

    // varは再代入可能な宣言
    a = 3 // このように再代入可能

    // varではなくvalも使える。valで宣言した場合は再代入不可
    val b: Int = 2
    b = 3 // bはvalで宣言しているため再代入不可、このコードはコンパイルエラーとなる

    // 型推論もあるため以下のようにも書ける(型の省略が可能)
    var c = 10

    // Kotlinではデフォルトでnullを許容していない(null安全)
    var d: String = null // このコードはコンパイルエラーとなる

    // nullで初期化したい場合は、型の後ろに?を付ける
    var e: String? = null
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした