Issue
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
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 -> 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")
Answered By - Mark
Answer Checked By - Robin (JavaFixing Admin)