首页 > 解决方案 > 许多可为空的对象,如何在路径末尾设置属性

问题描述

假设我们必须在对象“ObjectD”上设置属性。要获得这个对象,我们必须通过可空对象的路径:

objectA.objectB?.objectC?.objectD?.property = 1234

问题是,必须检查每个对象,如果为空则应该创建。

如果没有 if 语句,有没有办法做到这一点?

if (objectA.objectB == null) {
    objectA.objectB = ObjectB().apply {
        objectC = ObjectC().apply {
            objectD = ObjectD().apply {property = 1444}
        }
    }
} else {
    if (objectA.objectB.objectC == null) {
        objectA.objectB.objectC = ObjectC().apply {
            objectD = ObjectD().apply {property = 144}
        }
    }
}

标签: kotlin

解决方案


为此,我认为,您应该创建类似getOrCreateObjectB(): ObjectB. 如果您能够更改这些对象的内部 - 将此方法作为类成员函数,如果不能 - 作为扩展。扩展示例如下:

fun ObjectA.getOrCreateObjectB(): ObjectB {
    if (objectB == null) objectB = ObjectB()
    return objectB
}

最终,你会得到这样的结果: objectA.getOrCreateObjectB().getOrCreateObjectC().getOrCreateObjectD().property = 1234


推荐阅读