Parceable readString() nullable warning

Viewed 1835

Since the latest update Android Studio gives me following warning:

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

This warning shows up at following code snipped:

data class Person(

    @SerializedName("surname")
    surname : String

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

There are to way to fix it, and hide this warning:

First is to make value type nullable, which means changing String to String?.

Second is to make readString always return non-null value - readString()!!

My question is which approach is better. Is it possible that readString will return null, if the value can't be nullable?

1 Answers

It's much easier, actually

Inside application's build.gradle

androidExtensions {
    experimental = true
}

And change your class like this:

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

As for your question – none, actually. The best way to handle situation like yours is either:

  1. to write parcel.readString() ?: "", meaning if result it null, it will return empty string
  2. to write parcel.readString() ?: throw IllegalStateException("Error happened, do something"), meaning it will throw an exception and you don't have to deal with any nullability at all.

Personally, I'd stick with option #1

Related