有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何验证kotlin中的数据类是否为null

我有一个数据类(如下所示)

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 }
}

如何直接在kotlin中检查请求是否为空


共 (1) 个答案

  1. # 1 楼答案

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

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

    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实现