Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return null from fun in kotlin

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

It gives me kotlin.KotlinNullPointerException.

Can anyone tell me how can I solve this?

like image 330
Sundeep Badhotiya Avatar asked Sep 07 '17 14:09

Sundeep Badhotiya


1 Answers

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

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()
}
like image 156
Maroš Šeleng Avatar answered Oct 08 '22 02:10

Maroš Šeleng