【问题标题】:Only safe or non-null asserted calls are allowed on a nullable receiver of type String?String 类型的可空接收器只允许安全或非空断言调用?
【发布时间】:2020-05-31 05:50:41
【问题描述】:

我的 api 响应有如下数据类

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
)

我的 api 调用

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

在尝试获取 userId 时,我得到了

在可空对象上只允许安全或非空断言调用

【问题讨论】:

  • 您的数据类变量var userId: String? = null 可以为空。不能直接拨打response.body().userId,加!!到最后 response.body().userId!! 但如果 userId 值为 null,这将导致 nullPointerException。更多详情请参考kotlinlang.org/docs/reference/null-safety.html

标签: android kotlin data-class


【解决方案1】:

您已在模型类中将userId 定义为optional or nullable,方法是在类型前面放置?

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

因此,当从response.body() 读取值时,它会告诉您response.body() 中的值userId 可能为空,并且会在运行时抛出null-pointer exception。因此,为了保护它,它为您提供了两种选择:

1) Only safe userId? -> 这意味着如果该值为 null,那么它将不会继续执行该特定行。

2) Non-null asserted userId!! -> 意味着你告诉编译器它永远不会为空,并且你保证如果这个值有任何机会为空,那么它会抛出一个运行时null-pointer exception

因此,最佳做法是为 Only Safe 设置一个 ? 并以这种方式使用它,因为如果它始终是 not-null 不会有任何区别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多