How can I declare a property with a custom setter, but without getter in Kotlin? In Anko for example they do it like this:
var myProperty: Type
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR)
get() = AnkoInternals.noGetter()
set(value) { field = value; /* setter logic */ }
But it looks a bit hacky to me. Is this a right way to do so? If yes, then what about the case when a project doesn't have Anko dependency?
P.S. Let me be clear - I want to have no getter at all, rather than private getter
In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.
Properties. Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword. By default, all properties and functions in Kotlin are public.
In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let's define a property 'name', in a class, 'Company'. The data type of 'name' is String and we shall initialize it with some default value.
The default getter and setter is a familiar pattern we see in Java, but in Kotlin, we don’t have to create a private backing field for the property. We can use dot syntax to call the getter and setter for class properties:
Introduction In this tutorial, we’re going to look at properties in Kotlin and how to access them. Properties are similar to fields in Java, but there are some important differences. For example, properties have auto-generated getters and setters. They can also be declared at the top-level package scope – they don’t have to belong to a class. 2.
Kotlin properties can be declared either as mutable using the var keyword or as immutable using the val keyword. Here, the property initializer, getter and setter are optional. We can also omit the property type, if it can be inferred from the initializer.
Here, property initializer, getter and setter are optional. Following is an example of the same: By default, all properties and functions in Kotlin are public. But in case of private and protected, you have to add it explicitly. Also, all properties in Kotlin are final by default.
Deprecating the getter is still the only way to get the effect.
You don't need an Anko dependency, just use the @Deprecated
annotation with an appropriate level
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With