Home > OS >  Kotlin Receiver Name Clash
Kotlin Receiver Name Clash

Time:12-29

When running the following code snippet, the compiler is attempting to resolve the method isEmpty against a receiver defined in kotlin.collections for reasons I don't fully understand. The method isEmpty is defined within java.util.Optional. If I replace isEmpty with !isPresent, the code works as expected.

private fun getThreadCount(param: Optional<String>): Int {
        return if(param.isEmpty) {
            DEFAULT_THREAD_COUNT
        } else {
            val threads = param.get()
            try {
                threads.toInt()
            } catch (ex: NumberFormatException) {
                throw RuntimeException("Failed to parse threads parameter: $threads")
            }
        }
    }
> Task :compileKotlin FAILED
e: /home/.../TaskParams.kt: (51, 25): Function invocation 'isEmpty(...)' expected
e: /home/.../TaskParams.kt: (51, 25): Unresolved reference. None of the following 
candidates is applicable because of receiver type mismatch: 
public inline fun <T> Array<out ???>.isEmpty(): Boolean defined in kotlin.collections
public inline fun BooleanArray.isEmpty(): Boolean defined in kotlin.collections
public inline fun ByteArray.isEmpty(): Boolean defined in kotlin.collections
public inline fun CharArray.isEmpty(): Boolean defined in kotlin.collections
public inline fun CharSequence.isEmpty(): Boolean defined in kotlin.text
public inline fun DoubleArray.isEmpty(): Boolean defined in kotlin.collections
public inline fun FloatArray.isEmpty(): Boolean defined in kotlin.collections
public inline fun IntArray.isEmpty(): Boolean defined in kotlin.collections
public inline fun LongArray.isEmpty(): Boolean defined in kotlin.collections
public inline fun ShortArray.isEmpty(): Boolean defined in kotlin.collections

This is being compiled against Kotlin 1.3.72

CodePudding user response:

java.util.Optional isEmpty() was added in Java 11. The Android version of Optional (or whatever your target is) does not have it.

Just go with the !isPresent(), or !isPresent with kotlin syntax sugar.

  • Related