Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to resolve conflicting overloads in Kotlin

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

how can i resolve the conflicting overloads error

>Solution :

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          -> 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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading