简体   繁体   English

Kotlin 接收器名称冲突

[英]Kotlin Receiver Name Clash

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.运行以下代码片段时,编译器尝试解析方法isEmpty针对kotlin.collections中定义的接收器,原因我不完全理解。 The method isEmpty is defined within java.util.Optional .方法isEmptyjava.util.Optional中定义。 If I replace isEmpty with !isPresent , the code works as expected.如果我将isEmpty替换为!isPresent ,则代码将按预期工作。

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这是针对 Kotlin 1.3.72 编译的

java.util.Optional isEmpty() was added in Java 11. The Android version of Optional (or whatever your target is) does not have it. java.util.Optional isEmpty()被添加到 Java 11. Android 版本的Optional (或任何你的目标没有)。

Just go with the !isPresent() , or !isPresent with kotlin syntax sugar.只需 go 与!isPresent()!isPresent与 kotlin 语法糖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM