Kotlin:相互指派

CSJ*_*CSJ 5 immutability kotlin

我想设置两个值,彼此保持不可变的引用.例:

data class Person(val other: Person)
val jack = Person(jill), jill = Person(jack)   // doesn't compile
Run Code Online (Sandbox Code Playgroud)

注意:lateinit似乎不适用于数据类主构造函数.

有任何想法吗?

jiv*_*erg 2

你可以逃避这样的事情:

class Person() {
    private var _other: Person? = null

    private constructor(_other: Person? = null) : this() {
        this._other = _other
    }

    val other: Person
        get() {
            if (_other == null) {
                _other = Person(this)
            }
            return _other ?: throw AssertionError("Set to null by another thread")
        }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样做:

val jack = Person()
val jill = jack.other
Run Code Online (Sandbox Code Playgroud)

由于多种原因,在此处使用 adata class不起作用:

  1. 首先因为 adata class不能有空的构造函数。

  2. 即使这不是问题,生成的方法最终也会产生循环依赖,并且会在运行时失败java.lang.StackOverflowError。因此,您必须覆盖toStringequals等,这首先就违背了使用的目的。data class