在 Kotlin 中创建接口时,属性是否具有 get/set 是否重要?

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

在 Kotlin 接口中,如果使用空 get/set 语句声明属性是否重要?

例如...

interface ExampleInterface {
    // These...
    val a: String
        get
    var b: String
        get
        set

    // ...compared to these...
    val c: String
    var d: String
}

我很难注意到差异。

在实现接口的时候,属性是用getters/setters,还是直接设置值,好像都无所谓

当通过 java 访问它们时,val 都有 getter,var 都有 getter 和 setter。

public void javaMethod(ExampleInterface e) {
    e.getA();

    e.getB();
    e.setB();

    e.getC();

    e.getD();
    e.setD();
}

示例中的 属性 声明是相同的,getset 可以安全地从那里删除,因为正如您正确指出的那样,无论如何都会生成访问器。但是,getset 的语法可用于提供访问器实现或限制其可见性。

  • 提供实现:

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

    此示例显示了在接口中声明的 属性 的默认实现。这个 属性 仍然可以在接口实现中被覆盖。

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

    此处,get() = ... 覆盖了带有支持字段的 属性 的默认 getter 行为,而未提及 set,因此它表现正常。

  • 可见性限制:

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

    在此示例中,setter 可见度为 privateget 的可见性始终与 属性 的可见性相同,因此无需单独指定。接口不能声明 private 个成员。

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

    此 属性 的 setter 仅限于此 class 及其子 class。接口不能声明 protected 成员。

当然,访问器实现可以与可见性限制相结合:

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

另请参阅: