Write to a pair zero value in kotlin

Backend returns nullable Int? How to write a value with a zero value?

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

Now I got the solution:

 dest.writeInt(value?: -1) 

And then set the value to -1

or write Int as a string, and then use the value ...

but I find it ugly and wrong.

SOLVED! My answer:

 source.readValue(Int::class.java.classLoader) as Int?, dest.writeValue(value) 
+6
source share
3 answers

It is decided:

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

This largely depends on what the semantics of null as values ​​of the nullable property. It could mean:

  • If value is null, it is absent and should not be written at all:

     value?.let { writeInt(it) } 

    Of course, the Parcel receiver should be able to determine whether it should read the value or not, this should be clear from the values ​​written earlier.

  • value provided by some code, and this is an error if it is zero at the point where it should be written:

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

    Also, in this case, consider using lateinit var instead of the nullable property.

  • Instead of value , use the default value:

     writeInt(value ?: someDefaultValue()) 

    With Parcel this makes sense, because otherwise, if the value is missing, you must indicate the fact somewhere else.

  • ... ( null can actually mean a lot of things)

In addition, this answer shows many idiomatic ways to use values ​​with a zero value, and you may find some of them useful.

+2
source

See what Google Play services use to safely display zero lines:

 String NULL = "SAFE_PARCELABLE_NULL_STRING"; 

This is technically not an empty string; the team decided that semantically this string is zero.

We use similar methods when working with lists. First we writeInt with the length of the list. It can be -1 so that the list is empty.

Whether -1 can be used to represent the absence of an integer depends on your schema. In your use case -1 valid value? If so, you should find another value to represent your null value, such as Int.MIN or Int.MAX .

If all of these values ​​are in the valid range, use a different value, for example:

 val hasValue: Boolean = value != null val hasValueByte: Byte = if (value != null) 1 else 0 dest.writeByte(hasValueByte) if (hasValue) dest.writeInt(value) 

Do not forget about one of these cases when unmarshalling!

 val parcelHasValueByte = source.readByte() val parcelHasValue = parcelHasValueByte != 0 if (parcelHasValue) { value = source.readInt() } else { value = null } 
+1
source

Source: https://habr.com/ru/post/1014458/


All Articles