我有一个数据类(如下)
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
的实现。