Reputation: 2951
In kotlin, we can define
var text: String
which will have a getter and a setter. It's easy to remove the setter by changing it to val
, but what if we have a property that should only have the setter and no getter? Is there any way to create an annotation that we can apply to text
that will deprecate the getter so others cannot use it?
The end goal is to be able to use the property syntax rather than call setText
Current workaround I am aware of that achieves a similar result:
var text: String
@Deprecated(level = DeprecationLevel.ERROR, message = "Non readable property")
get() = nonReadable()
set() ...
I would like to know if it's possible to define something similar to
@SetterOnly
var text: String
set() ...
Upvotes: 4
Views: 1226
Reputation: 389
If you don't want this property to be used externally, why dont you declare it as
private var text :String =""
Upvotes: 0
Reputation: 30686
I can tell you that there is no way to complete this feature in kotlin now. since the bug KT-3110 is not marked as Fixed
.
I have test the following java code in kotlin at below, it only can access setter via setText
:
public class Property {
public void setText(String text) {/**/}
private String getText() { return "foo"; }
}
which means you can't remove the getter/make the getter's visibility down. so it is impossible to get rid of the getter
like as kotlin-allopen
plugin. so one possible solution you can do is write your own kapt plugin to throws a compile-time error, for example:
@SetOnly var text:String = "foo";
Upvotes: 1