Home > Mobile >  How to resolve conflicting overloads in Kotlin
How to resolve conflicting overloads in Kotlin

Time:08-11

Im my current Android application i am trying to implement the following extension functions to handle any type of intent extra

fun Activity.extraNotNull(key: String): Lazy<String> = lazy {
    val value: String? = intent?.extras?.getString(key)
    requireNotNull(value) { MISSING_MANDATORY_KEY   key }
}
 
fun Activity.extraNotNull(key: String): Lazy<Long> = lazy {
    val value: Long? = intent?.extras?.getLong(key)
    requireNotNull(value) { MISSING_MANDATORY_KEY   key }
}

however i am getting the following compile time error

enter image description here

how can i resolve the conflicting overloads error

CodePudding user response:

As mentioned its not possible to overload methods with identical signatures and different return types - there is no way to differentiate what method you are calling.

A better solution is to make generic function that would support all types, something like this would be a good starting point :

inline fun <reified T> Activity.extraNotNull(key: String): Lazy<T> = lazy {
    val value: T? = intent?.extras?.let { x ->
        when (T::class) {
            String::class  -> x.getString(key)
            Long::class    -> x.getLong(key)
            Float::class   -> x.getFloat(key)
            Double::class  -> x.getDouble(key)
            else           -> throw IllegalArgumentException("not a valid data type ${T::class}")
        } as? T
    }
    requireNotNull(value)
}

Usage :

val s: String by extraNotNull("a")
val l: Long by extraNotNull("b")
val f: Float by extraNotNull("c")
val d: Double by extraNotNull("d")

CodePudding user response:

You can't do that. Method overloading won't work if you only change the return type. You need to add/remove some of the parameters.

  • Related