[英]Kotlin initialization: how to fail
I need to parse Firebase DataSnapshot
(a JSON object) into a data class, whose properties include enum and list. 我需要将Firebase DataSnapshot
(一个JSON对象)解析为一个数据类,其属性包括枚举和列表。 So I prefer parsing it manually by passing the DataSnapshot
into a secondary constructor. 所以我更喜欢通过将DataSnapshot
传递给辅助构造函数来手动解析它。 However, I want the construction to fail if some fields are missing in the DataSnapshot
. 但是,如果DataSnapshot
中缺少某些字段,我希望构造失败。 In Swift, it has failable initializer that returns null so I know it has failed. 在Swift中,它有可用的初始化程序,它返回null,所以我知道它已经失败了。 How to do that in Kotlin? 如何在Kotlin做到这一点?
The following is my attempt, but I assume you can't just return from a constructor, right? 以下是我的尝试,但我认为你不能只是从构造函数返回,对吧?
data class Unit(val name: String, val type: UnitType, val components: List<Component>) {
constructor(snapshot: DataSnapshot) {
name = snapshot.child("name").value as? String ?: return
val typeString = snapshot.child("type").value as? String ?: return
type = UnitType.values().firstOrNull { it.abbrv == typeString } ?: return
...
}
}
There is the require
function which was designed for this purpose: 有为此目的设计的require
函数:
// ...
init {
require(foo == "bar") {
"$foo should be equal to 'bar'"
}
}
There is also requireNotNull
, check
, error
and some others. 还有requireNotNull
, check
, error
和其他一些。 These are called Preconditions in Kotlin. 这些在Kotlin中被称为先决条件 。 There is no magic here, they are just some helper functions. 这里没有魔法,它们只是一些辅助功能。 You can check the actual source here , it is very useful. 您可以在这里查看实际来源,非常有用。 There is a related blog post about the topic here . 有一个关于该主题相关的博客文章在这里 。
No, you can't just return from a constructor - it doesn't make much sense conceptually - but since I'm fairly naive on Kotlin syntax, I'll answer to a more broad paradigm here. 不,你不能只是从构造函数返回 - 它在概念上没有多大意义 - 但由于我对Kotlin语法相当天真,我将在这里回答更广泛的范例。
Your data class is not responsible for error checking or error handling. 您的数据类不负责错误检查或错误处理。 It is only responsible for storing data. 它只负责存储数据。 Therefore, you should rely on a factory pattern to parse the result of a DataSnapshot
and conditionally instantiate a new instance of Unit
if and only if no fields are missing. 因此,当且仅当没有缺少字段时,您应该依赖工厂模式来解析DataSnapshot
的结果并有条件地实例化Unit
的新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.