在 kotlin 中写入 parcer 可为空的值

Write in parcer nullable value in kotlin

后端 returns 可为空 Int? 可空值应该怎么写?

 date class Foo (var value: Int?){
   constructor(source: Parcel) : this(
     source.readInt()
   )

   override fun writeToParcel(dest: Parcel, flags: Int) {
     dest.writeInt(value) // doesn't compile - writeInt expect no null value
   }
 }

现在我得到了解决方案:

dest.writeInt(value?: -1)

然后检查到-1

或者像字符串一样写 Int 然后使用值...

但我认为这是丑陋和错误的。

已解决!我的回答:

source.readValue(Int::class.java.classLoader) as Int?,
dest.writeValue(value)

这在很大程度上取决于 null 作为可空值 属性 的语义。它可以表示:

  • 如果 value 为 null 那么它不存在并且根本不应该写:

    value?.let { writeInt(it) }
    

    当然,Parcel接收器应该能够判断是否应该读取这个值,这个从前面写的值应该就清楚了。

  • value是一些代码提供的,如果在应该写的地方为null则报错:

    check(value != null) { "value should be not null at the point it's wriiten" }
    writeInt(value!!)
    

    此外,在这种情况下,请考虑使用 lateinit var 而不是可为空的 属性。

  • 应该使用一些默认值而不是value:

    writeInt(value ?: someDefaultValue())
    

    对于 Parcel,这确实有意义,因为否则,如果缺少该值,您必须在其他地方指定事实。

  • ...(null实际上可以表示很多东西)

此外, 展示了许多处理可为空值的惯用方法,您可能会发现其中一些有用。

解决者:

source.readValue(Int::class.java.classLoader) as Int?,
dest.writeValue(value)

将 data 关键字与 Parcelable 一起使用,

@Parcelize
data class CallIssue(
                  var name : String? =null,
                  var status: String? = null ,
                  var mobile: String? = null,
                  var priority: Int = 0,
                  var natureOfWork: String? = null,
                  var department: String? = null,
                  var village: String? = null,
                  var time_reported: Date? = null,
                  var reporter: String? = null,
                  var assignee: String? = null,
                  var issue_id: String? = null,
                  var startDate: Date? = null,
                  var endDate: Date? = null,
                  var gender : String?= null,
                  var description: String? = null,
                  var commentList: List<String>? = null,
                  var expanded: Boolean = false) : Parcelable

如果您使用@Parcelize 然后使用"data" 关键字,否则当您将数据从一个activity 传递到另一个activity.

之后所有值都为空