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

Kotlinの変数をクラス内でのみ変更可能にする方法

More than 1 year has passed since last update.

Kotlinで単純に再代入不可にしたい場合はvalを使えばいいですが、以下のような内部で変更可能なgetterのみのクラスを作る方法がわからなかったので調べてみました。

Curry.java
public class Curry {
    private String spice = "トウガラシ";

    public String getSpice() {
        return spice;
    }

    private void changeSpice() {
        spice = "ショウガ";
    }
}

方法

Kotlinの変数はプロパティなので、setterをprivateにして外部から使用できなくすればいいです。

    var spice : String = "トウガラシ"
        private set

上のJavaのクラスをKotlinで書いた場合

Curry.kt
class Curry {
    var spice : String = "トウガラシ"
        private set

    private fun changeSpice() {
        spice = "ショウガ"
    }
}

外部からは参照のみで代入はできません。

Main.kt
fun main(args: Array<String>) {
    val curry = Curry()

    // 読み取り可能
    println(curry.spice)

    // 代入不可 コンパイルエラー
    curry.spice = "胡椒"
}
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
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