Search code examples
androidkotlinenumsparcelableparcel

@Parcelize and enum classes - Overload resolution ambiguity


I need a clarification about @Parcelize annotation in Kotlin. I've declared this enum class:

 @Parcelize
 enum class Source : Parcelable {
    LIST, MAP
 }

The class is annotated with @Parcelize in order to implement Parcelable interface and it's working fine, however when I try to pass the Parceled class in an intent I have to force a re-casting to Parcelable, otherwise the compiler gives me a "Overload resolution ambiguity". error:

Overload resolution ambiguity. All these functions match. @RecentlyNonNull public open fun putExtra(name: String!, value: Parcelable!): Intent! defined in android.content.Intent @RecentlyNonNull public open fun putExtra(name: String!, value: Serializable!): Intent! defined in android.content.Intent

val intent = Intent(context, DestinationActivity::class.java)
intent.putExtra(Constants.RETAIL_DETAILS_CLICK_SOURCE_ID, StoreDetailsClicked.Source
                    .MAP as Parcelable)

Why is the compiler giving me this error?


Solution

  • This is because enums are Serializable by default, and when you add Parcelable, it matches both method signatures. You can add an extension function to resolve the ambiguity:

    fun Intent.putParcelableExtra(key: String, value: Parcelable) {
        putExtra(key, value)
    }
    
    intent.putParcelableExtra(
        Constants.RETAIL_DETAILS_CLICK_SOURCE_ID, 
        StoreDetailsClicked.Source.MAP
    )