Search code examples
androidkotlindata-class

Only safe or non-null asserted calls are allowed on a nullable receiver of type String?


I have data class for my api response as below

data class ApiResponse(
@SerializedName("ErrorCode") @Expose
var errorCode: Int = 0,
@SerializedName("Message")
@Expose
var message: String? = null,

@SerializedName("Token")
@Expose
var token: String? = null,

@SerializedName("UserId")
@Expose
var userId: String? = null,

@SerializedName("DOB")
@Expose
var birthdate: String? = null,

@SerializedName("Mobile")
@Expose
var mobile: String? = null,

@SerializedName("Data")
@Expose
var dataList: MutableList<Data?>? = null
)

My api call

val request = ApiServiceBuilder.buildService(NetworkCall::class.java)
    request.login(apiPost = ApiPost("long","hello")).enqueue(object :Callback<ApiResponse>{
        override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
            Log.e("resopne",response.body().userId)
        }

        override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
            t.printStackTrace()
            Log.e("resopne","error")
        }
    })

While try to get userId I get

Only safe or non-null asserted calls are allowed on a nullable


Solution

  • You have defined userId in your model class as optional or nullable by putting a ? in the front of the type.

    @SerializedName("UserId")
    @Expose
    var userId: String? = null
    

    So when reading a value from the response.body() it's telling you that the value userId inside your response.body() could be null and will throw a null-pointer exception in runtime. So, to protect it it is giving you two options:

    1) Only safe userId? -> This means that if the value is null then it will not continue execution of that particular line.

    2) Non-null asserted userId!! -> Means you are telling the compiler that it will never be null and you guarantee that so if by any chance this value gets null then it's gonna throw a runtime null-pointer exception.

    So, best practices are you put a ? for Only Safe and use it that way because it's not gonna make any difference if it is not-null always.