构建错误:类型不匹配:推断类型为 Unit

cev*_*ing 1 type-mismatch kotlin

我尝试连接一些条形码值:

barcodeScanner.process(image)
    .addOnSuccessListener {
        barcodes ->
            if (barcodes.isNotEmpty()) {
                val barcode = barcodes.reduce {acc, barcode -> acc + barcode.rawValue() }
                debug ("analyze: barcodes: $barcode")
            } else {
                debug ("analyze: No barcode scanned")
            }
    }
Run Code Online (Sandbox Code Playgroud)

该代码产生以下错误:

barcodeScanner.process(image)
    .addOnSuccessListener {
        barcodes ->
            if (barcodes.isNotEmpty()) {
                val barcode = barcodes.reduce {acc, barcode -> acc + barcode.rawValue() }
                debug ("analyze: barcodes: $barcode")
            } else {
                debug ("analyze: No barcode scanned")
            }
    }
Run Code Online (Sandbox Code Playgroud)

我都不明白他们的意思。有人能解释一下吗?

特别是最后一条错误消息对我来说听起来很奇怪。为什么我要尝试调用rawValuea String?该变量barcodes的类型应该是List<Barcode>,而不是List<String>

Ruu*_*man 6

看一下reduce的函数原型

inline fun <S, T : S> Array<out T>.reduce(
    operation: (acc: S, T) -> S
): S
Run Code Online (Sandbox Code Playgroud)

的两个参数operation必须具有相同的类型,或者至少必须存在从第二个参数(即条形码)到第一个参数(acc)的隐式转换。

这是必要的,因为reduce使用列表的第一个元素作为累加器的初始值。

在您的情况下,数组元素是Barcode,而累加器是String。您可能想使用fold而不是reduce. 使用fold,您可以自由选择累加器的类型,因为您明确指定了累加器的初始值。在你的情况下,这将是空字符串。

另请参阅: Kotlin 中的折叠和减少的区别,何时使用哪个?