What is the correct way to define a var in kotlin that has a public getter and private (only internally modifiable) setter?
Asked
Active
Viewed 8.5k times
2 Answers
416
var setterVisibility: String = "abc" // Initializer required, not a nullable type
private set // the setter is private and has the default implementation

D3xter
- 6,165
- 1
- 15
- 13
-
29Note that `private set` must be on a new line. – Jasper Blues Jan 08 '16 at 04:36
-
60...or on the same line, after a semicolon: `var abc: String = ""; private set` – Boris B. Nov 29 '16 at 15:49
-
6I'm at a loss for what to do with a primary constructor field though. – androidguy Jan 08 '17 at 07:28
-
@user3175580 You mean how to create a private setter on a primary constructor property? – D3xter Jan 12 '17 at 21:46
-
@D3xter precisely – androidguy Jan 13 '17 at 02:10
-
5@user3175580 This is not possible. Use a local field inside the primary constructor and then assign the value to the property like "class Foo(_bar: String) { var bar: String = _bar } – D3xter Jan 13 '17 at 11:01
-
3@JasperBlues ...otherwise, you need to add semicolon before `private set`. – Moses Aprico Jun 22 '17 at 17:25
-
2I like the swift style a little better - `private(set) var abc : String = ""` – Jasper Blues Jun 22 '17 at 21:51
-
1@androidguy Here a discussion about possible future syntax to have "Private setter for var in primary constructor" https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640/13 – mcoolive Jul 01 '19 at 15:38
-
1Semicolon? In Kotlin? What blasphemy is this? /s – Some Noob Student Apr 10 '20 at 18:02
-
What about if you want to use an observable with a private setter? ie: so you can perform some reactive logic when the value is set? – Marchy Sep 28 '20 at 19:34
-
So the variable is public if you need to read its value, but it is private when attempting to set its value, hence, you cannot directly sets its value from the outside. Okay... – daparic Jul 21 '21 at 03:29