kotlin - 许多可为空的对象,如何在路径末尾设置属性
问题描述
假设我们必须在对象“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}
}
}
}
解决方案
为此,我认为,您应该创建类似getOrCreateObjectB(): ObjectB
. 如果您能够更改这些对象的内部 - 将此方法作为类成员函数,如果不能 - 作为扩展。扩展示例如下:
fun ObjectA.getOrCreateObjectB(): ObjectB {
if (objectB == null) objectB = ObjectB()
return objectB
}
最终,你会得到这样的结果:
objectA.getOrCreateObjectB().getOrCreateObjectC().getOrCreateObjectD().property = 1234
推荐阅读
- c++ - 节点指针数组
- javascript - options.domAPI 不是函数
- javascript - VS2019 捆绑和缩小导致 ES6 代码错误并且不会缩小
- swift - 参数类型“AnyObject.Protocol”应为类或类约束类型的实例
- javascript - 如何在 React/React-Native 的 React-navigation 中用上下文包装几个屏幕?
- azure - Azure Databricks 笔记本未通过 YAML deploynotebooks@0 任务部署
- linked-data - 在 shacl 验证报告中同时显示自定义消息和默认消息
- ithit-webdav-server - ITHit WebDAV - 编辑 Office 文档错误
- javascript - ReactJS:重定向到主页
- bootstrap-multiselect - 更改引导多选数据提供程序不会刷新小狗位置