拼接Barcode值时出现多类代码错误,求原因解析
条码拼接代码错误原因分析与修复
问题背景
尝试拼接扫描到的条码值,编写了如下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") } }
运行后出现以下编译错误:
Type mismatch: inferred type is Unit but Barcode! was expected Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public operator fun Offset.plus(offset: IntOffset): Offset defined in androidx.compose.ui.unit public operator fun IntOffset.plus(offset: Offset): Offset defined in androidx.compose.ui.unit Expression 'rawValue' of type 'String?' cannot be invoked as a function. The function 'invoke()' is not found
错误原因详解
1. Expression 'rawValue' of type 'String?' cannot be invoked as a function
rawValue是Barcode类的属性(而非函数),正确获取值的方式是barcode.rawValue,你错误地加了括号barcode.rawValue(),编译器会认为你要调用一个名为rawValue的函数,但实际上它是String?类型的属性,因此触发该错误。
2. Unresolved reference. None of the following candidates is applicable because of receiver type mismatch
当你写acc + barcode.rawValue()时,编译器找不到Barcode类型与String类型相加的plus操作符定义。于是它会全局查找可用的plus函数,结果只匹配到Offset相关的plus方法,但你的acc是Barcode类型,和Offset类型不匹配,因此报这个错误。
3. Type mismatch: inferred type is Unit but Barcode! was expected
reduce函数要求lambda的返回值类型必须和集合元素类型一致(这里是Barcode)。但你的lambda试图执行Barcode与String的非法相加操作,导致lambda无法返回符合要求的Barcode类型,编译器推断返回值为Unit,与reduce期望的Barcode类型不匹配,因此触发类型错误。
修复后的代码
你需要的是拼接条码的字符串值,而非合并Barcode对象,因此应该使用joinToString来实现:
barcodeScanner.process(image) .addOnSuccessListener { barcodes -> if (barcodes.isNotEmpty()) { // 拼接所有条码的rawValue,处理可能的空值 val barcodeStr = barcodes.joinToString("") { it.rawValue ?: "" } debug("analyze: barcodes: $barcodeStr") } else { debug("analyze: No barcode scanned") } }
内容的提问来源于stack exchange,提问作者ceving
相关产品推荐
相关产品推荐

