4

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?

Kacper Kogut
  • 707
  • 6
  • 15
  • The second one is the better approach. – Sunny Sep 05 '18 at 12:53
  • 1
    @Sunny the whole point is to avoid NPE. That way there is literally no reason to use `!!`, because `readString` clearly can produce `null`. Use of `!!` is ok when smart cast can't check legibility of expression at run time and you are 100% sure there can't be `null` – jujka Sep 05 '18 at 13:09

1 Answers1

5

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

jujka
  • 1,190
  • 13
  • 18
  • 1
    Here's a good perspective why you won't ever need to write your own `Parseable` ever again https://proandroiddev.com/parcelable-in-kotlin-here-comes-parcelize-b998d5a5fcac – jujka Sep 05 '18 at 13:03