从Kotlin的乐趣中返回null [英] Return null from fun in kotlin
本文介绍了从Kotlin的乐趣中返回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的乐趣中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文