LoginSignup
6

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-01-08

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 = "胡椒"
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6