簡體   English   中英

Kotlin中開放屬性有什么用?

[英]What is the use of open properties in Kotlin?

我一直在學習 Kotlin 並遇到了開放屬性的概念。 來自 C++,“開放”的概念是有道理的,並且將該邏輯擴展到屬性也是如此。 但是,我想不出任何實際需要或有用的open val / var情況。 我理解它們什么時候對接口有意義,但對具體類沒有意義。 此外,覆蓋 getter/setter 是有道理的,但不能用新的支持字段重新定義屬性。 例如,假設您有這種類結構:

open class Foo {
    open var str = "Hello"
}


class Bar : Foo() {
    override var str = "world" 

    init {
        println(str)
        println(super.str) // Shows that Bar actually contains "hello" and "world"
    }
} 

對我來說,讓 Foo 將str作為構造函數參數似乎是一個更好的設計,例如:

open class Foo(var str = "Hello") // Maybe make a secondary constructor

class Bar : Foo("world") // Bar has only 1 string

這更簡潔,而且似乎通常是更好的設計。 這也是它傾向於在 C++ 中完成的方式,所以也許我只是沒有看到其他方式的好處。 我可以看到用新的覆蓋val / var的唯一可能的時間是,如果出於某種原因需要使用super的值,例如

    override val foo = super.foo * 2

這似乎仍然很做作。

你什么時候發現這很有用? 它是否允許更高的效率或易用性?

open字段讓您重新定義 getter 和 setter 方法。 如果您只返回常量,這實際上毫無意義。 然而,改變 getter / setter 行為具有(無限)潛力,所以我只會提出一些想法:

// propagate get/set to parent class
class Bar : Foo() {
    override var str
        get() = super.str.toUpperCase()
        set(value) {
            super.str = value
        }
}

// creates a backing field for this property
class Bar : Foo() {
    override var str = "World"
        get() = field.toLowerCase()
        // no need to define custom set if we don't need it in this case
        // set(value) { field = value }
}

// instead of writing custom get/set, you can also use delegates
class Bar : Foo() {
    override var str by Delegates.observable("world"){ prop, old, new ->
        println("${prop.name} changed from $old to $new")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM