首页 文章

Kotlin: property 制定者的文件

提问于
浏览
7

我正在写一个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) 的行为应该对 SessionWrapper 的客户端透明,如果它们修改 expiryTime (即调用setter) .

现在,对于Kotlin项目,这不会是一个问题,因为我可以将额外的KDoc添加到 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() 中,感觉不对,因为我会 setter JavaDoc in the getter, and getter JavaDoc in the setter .

尝试以下列方式在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 referenceJava interop page中分离Java可见的getter和setter的文档 .

考虑到Kotlin与Java的良好互操作,我觉得这很烦人 .

会欣赏任何想法 .

1 回答

  • 2

    我认为你应该重新评估你的课程设计,而不是试图解释文档中的特殊行为 . 这通常是代码异味的标志,也可能是可测试性差的迹象 .

    您应该考虑到 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)
    }
    

    IMHO Kotlin的Java互操作性不应该导致代码就像Java代码一样 . 它在字节代码级别兼容,不一定在源代码和Javadoc级别上 .

相关问题