When creating an interface in Kotlin, does it matter if the get / set?

In the Kotlin interface, does it matter if properties are declared with an empty get / set statement?

For example...

interface ExampleInterface { // These... val a: String get var b: String get set // ...compared to these... val c: String var d: String } 

It’s hard for me to notice the difference.

When implementing the interface, it doesn't seem to matter if I use getters / seters for properties, or if I set the value directly.

When accessing these via java, val both have getters, and var have getters and seters.

 public void javaMethod(ExampleInterface e) { e.getA(); e.getB(); e.setB(); e.getC(); e.getD(); e.setD(); } 
+8
properties getter-setter kotlin
source share
1 answer

The property declarations in your example are identical, get and set can be safely removed from there, because, as you correctly noted, accessors are generated anyway. The syntax with get and set can, however, be used to provide access implementations or to limit its visibility.

  • Ensuring implementation:

     interface ExampleInterface { var b: String get() = "" set(value) { } } 

    This example shows the default implementation of a property declared in an interface. This property can still be overridden within interface implementations.

     class Example { var b: String = "" get() = "$field$field" } 

    Here get() = ... overrides the default getter behavior of a property with a support field, whereas set not mentioned, so it behaves normally.

  • Visibility Limit:

     class Example { var s: String = "s" private set } 

    In this example, the setter visibility is private . The visibility of get always the same for the visibility of a property, so there is no need to specify it separately. Interfaces cannot declare private members.

     abstract class Example { abstract var b: String protected set // Restrict visibility } 

    The installer of this property is limited to this class and its subclasses. Interfaces cannot declare protected members.

Of course, an access implementation can be combined with a visibility restriction:

 class Example { var s: String = "abc" private set(value) { if (value.isNotEmpty()) field = value } } 

See also:

+10
source share

All Articles