Parcelable readString() 可为空警告

Parceable readString() nullable warning

自从最新更新 Android Studio 给了我以下警告:

Expected type does not accept nulls in Kotlin, but the value may be null in Java

此警告出现在以下代码片段中:

data class Person(

    @SerializedName("surname")
    surname : String

) { 
    constructor(parcel: Parcel) : this(
        parcel.readString()
    )
    //Parceable implementation
}

有多种方法可以修复它并隐藏此警告:

首先是使值类型可以为空,这意味着将 String 更改为 String?.

其次是使 readString 始终 return 非空值 - readString()!!

我的问题是哪种方法更好。如果值不能为空,readString 是否可能 return 为空?

实际上要容易得多

内部应用程序的 build.gradle

androidExtensions {
    experimental = true
}

并像这样更改您的 class:

@Parcelize
data class Person(
    val surname: String
): Parcelable

至于你的问题——none,实际上。处理像您这样的情况的最佳方法是:

  1. parcel.readString() ?: "",意思是如果结果为null,它将return空字符串
  2. parcel.readString() ?: throw IllegalStateException("Error happened, do something"),这意味着它会抛出异常,您根本不必处理任何可空性。

就个人而言,我会坚持选项 #1