在 kotlin 中从 fun 中返回 null [英] Return null from fun in kotlin

查看:35
本文介绍了在 kotlin 中从 fun 中返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个函数来执行数据库查询.如果无法获取任何结果,我希望它返回 null.

I've written a function to perform a database query. I want it to return null if it cannot fetch any result.

fun getServiceCharge(model: String): ServiceChargeMasterList {
    val unique = VideoconApplication.daoSession.serviceChargeMasterListDao.queryBuilder().where(ServiceChargeMasterListDao.Properties.ModelCategory.eq(model)).unique()
    if (unique != null)
        return unique
    else
        return null!!
}

它给了我 kotlin.KotlinNullPointerException.

It gives me kotlin.KotlinNullPointerException.

谁能告诉我如何解决这个问题?

Can anyone tell me how can I solve this?

推荐答案

只需将返回类型指定为 ServiceChargeMasterList? 并返回 null.!! 操作符使用起来非常难看.

Just specify your return type as ServiceChargeMasterList? and return null. The !! operator is very ugly to use.

如果您的 unique() 方法返回和可选(或 Java 对象),您甚至不必使用该 if 语句.在这种情况下,您的方法可能如下所示:

You don't even have to use that if statement if your unique() method return and optional (or Java object). In that case, you method could look like this:

fun getServiceCharge(model: String): ServiceChargeMasterList? {
    return VideoconApplication.daoSession.serviceChargeMasterListDao.queryBuilder().where(ServiceChargeMasterListDao.Properties.ModelCategory.eq(model)).unique()
}

这篇关于在 kotlin 中从 fun 中返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆