如何在kotlin中验证数据类是否为空



我有一个数据类(如下)

data class Request(val containerType: String,
val containerId: String)

我在另一个函数中作为参数调用,如下所示

fun someLogicalFunction(request: Request) {
// validate if request is not null here
if(request == null) { // i know this is wrong, what can be done for this?
// do something
} else { // do something }
}

如何检查如果请求不是null直接在kotlin?

参数中Request的类型不可为空,因此不能将Request传递为空。更改为nullable,然后检查它是否为空就有意义了:

fun someLogicalFunction(request: Request?) {
// validate if request is not null here
if(request == null) { // i know this is wrong, what can be done for this?
// do something
} else { // do something }
}

someLogicalFunction的参数类型是非空的(与Request的属性相同),因此,如果从Kotlin代码调用它,您可以在编译时保证不会给出空值,并且没有必要进行空检查。

然而,如果你真的想要/需要允许null,我建议这样做

data class Request(val containerType: String?,
val containerId: String?) {
val isValid get() = containerId != null && containerType != null
}
fun someLogicalFunction(request: Request?) {
request?.let{
if (request.isValid) {
val type = request.containerType!!
val id = request.containerId!!
// do something
return //this will return out of someLogicalFunction
}
}
//we will only execute code here if request was null or if we decided it was invalid
}

显然是用对你需要的任何东西都有意义的东西替换isValid的实现。

相关内容

  • 没有找到相关文章

最新更新