簡體   English   中英

Kotlin:屬性設置程序的文檔

[英]Kotlin: Documentation for property setter

我正在寫Kotlin圖書館。 在其中一個課程中,我有以下內容:

class SessionWrapper {

    /**
     * The time in milliseconds after which the session will expire.
     */
    var expiryTime = DEFAULT_EXPIRY_TIME
        get() {
            mainThreadCheck()
            return field
        }
        set(value) {
            mainThreadCheck()
            field = value
            updateExpiry(value) <<< THIS ONE
        }

    ...
}

但是,如果updateExpiry(long)修改了expiryTime (即調用setter),則該行為對於SessionWrapper的客戶端應該是透明的。

現在,對於Kotlin項目,這將不再是問題,因為我可以將額外的KDoc添加到expiryTime屬性本身中,並且不會感到expiryTime

    /**
     * The time in milliseconds after which the session will expire.
     *
     * Updating the expiry time after the session is started does x,
     * the listeners will receive y.
     *
     * Writing comments is fun, when the tools work.
     */
     var expiryTime = DEFAULT_EXPIRY_TIME

但是對於Java項目,上面的文檔將同時出現在setExpiryTime(long)getExpiryTime() ,這讓人感覺很getExpiryTime() ,因為我將在getter中設置JavaDoc,在setter中設置JavaDoc

嘗試通過以下方式在Kotlin中分離兩個訪問者的文檔:

class SomeClass{

    var expiryTime = DEFAULT_EXPIRY_TIME
        /**
         * The time in milliseconds after which the session will expire.
         */
        get() {
            mainThreadCheck()
            return field
        }
        /**
         * Updating the expiry time after the session is started does x,
         * the listeners will receive y.
         *
         * Writing comments is fun, when the tools work.
         */
        set(value) {
            mainThreadCheck()
            field = value
            updateExpiry(value)
        }

    ...
}

對於Kotlin和Java代碼,在IDE中僅不顯示JavaDoc。

我沒有找到明確的方法來嘗試在KDoc參考Java interop頁面中分離Java可見的getter和setter的文檔。

考慮到Kotlin與Java的良好互操作,我覺得這很煩人。

將不勝感激任何想法。

我認為您應該重新評估您的類設計,而不是試圖解釋文檔中的特殊行為。 這通常是代碼氣味的跡象,也可能是可測試性差的跡象。

您應該考慮到updateExpiry()的特殊行為來對類進行updateExpiry() 如果這方面值得客戶端透明,則它可能應該是某種接口或協議步驟的一部分。

在不了解其余軟件細節的情況下,我能想到的最好的辦法就是將setter設為私有,並添加一個單獨的函數來更新expiryTime

/** Explain property */
var expiryTime = DEFAULT_EXPIRY_TIME
    get() {
        mainThreadCheck()
        return field
    }
    private set(value) {
        mainThreadCheck()
        field = value
    }

/** Explain update behavior constraints */
fun updateExpiryTime(value: Any) {
  expiryTime = value
  updateExpiry(value)
}

不應期望恕我直言Kotlin的Java互操作性會導致產生與Java代碼相似的代碼。 它在字節碼級別兼容,而不必在源代碼和Javadoc級別兼容。

暫無
暫無

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

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