简体   繁体   中英

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?

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

Use this

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

Explanation

In Kotlin, there are optional types . If you return ServiceChargeMasterList, you say to the compiler that you will never return null. If you want to return null, you have to add ? sign at the end of the type which indicates that you can return an instance of ServiceChargeMasterList or null.

The operator !! can be explained in Java as

//Kotlin
variable!!


//Java
if (variable == null)
    throw new kotlin.NullPointerException();

Your method's return type does not allow null to be returned. You need to change it to it's nullable version ServiceChargeMasterList? (nullability denoted by the question mark).

The not-null assertion operator !! should only be used in very rare cases because it tries to transform nullable types into non-nullable types and might throw a NullPointerException when invoked on null . Your code null!! is the perfect demonstration for this.

Instead of applying safe operators like in nullableVar?.foo() , this operator is used like this: nullableVar!!.foo() .

In your case though, the !! operator is the wrong choice. If your method is really supposed to return null , change the return type.

open fun getProfile() : ProfileModel? {
    if (MyApplication.sharedPreference.getString("profile","")!=null){
        var profileModel : ProfileModel = Profile()
        return profileModel
    }
    return null 
}

add ? after your return type then return null it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM