繁体   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