首页 文章

如何在kotlin数据类中将非可空属性初始化为this指针?

提问于
浏览
0

给定Kotlin数据类,如何将非可空属性初始化为指向self的指针?就像下面的伪代码一样 .

data class Node(var other: Node = this)

目前我有一个引入临时属性的解决方案

data class Node(val _other: Node? = null) {
    var other: Node = _other ?: this
}

2 回答

  • 2

    感谢您的反馈,但是,出于我的目的,我需要像equals和copy这样的数据类的功能,我宁愿不让属性可以为空和/或手动实现功能 .

    你仍然需要: equalscopy 只会关心 _other 而忽略 other (正如他们会忽略在类体中定义的所有其他属性一样) . othervar 只会使情况变得更糟:重新分配它对数据类功能没有影响 .

    但你可以走近一点:

    data class Node(private var _other: Node? = null) {
        var other: Node
            get() = _other ?: this
            set(value) {
                _other = if (value != this) value else null
            }
    }
    

    剩下的唯一问题是component1()将返回 _other . 在这种情况下,您有一个属性,所以它应该无关紧要 .

    编辑:经过多思考后,

    data class Node(private var _other: Node? = null) {
        init {
            this._other = _other ?: this
        }
    
        var other: Node
            get() = _other!! // safe
            set(value) {
                _other = value
            }
    }
    

    似乎有效地成为你想要的 . 你可以在这里看到差异:

    val node1 = Node()
    val node2 = node1.copy(node1)
    println(node1 == node2)
    

    使用第一个解决方案打印 false ,使用第二个解决方案打印 true (如果 this 是默认参数,则应该如此) .

  • 1

    这是不可能的 . 在构造之前,您无法访问 this . 但这就是默认构造函数参数的工作原理 .

    Cannot access '<this>' before superclass constructor has been called
    

相关问题