当前位置: 首页 > 知识库问答 >
问题:

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

安经纶
2023-03-14

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

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中检查请求是否不为null?

共有2个答案

鲁财
2023-03-14

someLogicalFunction的参数类型不可为null(与请求的属性相同),因此如果从Kotlin代码调用它,则可以在编译时保证不会给出null值,并且不需要进行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实现。

公冶泰
2023-03-14

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

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在spring-data-rest项目上使用JSR303验证。 给定以下数据类声明: 提前感谢您的帮助!

  • 我的控制器中有请求,是MongoId的字符串版本。如果我使用无效的字符串格式(与MongoId格式不匹配)调用此请求,则该请求将一直执行,直到MongoDB调用抛出内部服务器错误。 我如何验证,例如或"ANWPINREBAFSOFASD"未被验证,并在我的请求中尽早停止 电流控制器endpoint: 该服务称为:

  • 我试图在kotlin中为我的数据模型添加验证,使用注释很容易实现简单的字段。但是,我正在努力做同样的收藏。 我已经在这里将问题上传到了github 如有任何帮助,将不胜感激。谢谢你!

  • 我需要验证一个Map值是否为null,因为我经常使用集合,愿意实现验证Map值的通用方法,所以尝试了这个 有没有人能帮助我更深入地理解这个逻辑。

  • 问题内容: 使用SQLAlchemy ORM,我要确保值是其列的正确类型。 例如,假设我有一个Integer列。我尝试插入值“ hello”,它不是有效的整数。SQLAlchemy将允许我执行此操作。仅在稍后执行时,它才会引发异常:。 我要添加成批的记录,出于性能原因,我不想在每笔记录之后提交。 那么我该如何: 我尽快提出例外 或者,在将我添加的值添加到批处理 之前 ,确保将其转换为目标Colum