Home > OS >  Build error: Type mismatch: inferred type is Unit
Build error: Type mismatch: inferred type is Unit

Time:11-05

I try to concatenate some barcode values:

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")
            }
    }

The code produces the following errors:

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

I understand none of them. Can anybody explain?

In particular the last error message sounds strange to me. Why do I try to call rawValue on a String? The variable barcodes should be of the type List<Barcode> and not List<String>.

CodePudding user response:

Have a look at the function prototype of reduce:

inline fun <S, T : S> Array<out T>.reduce(
    operation: (acc: S, T) -> S
): S

The two parameters of operation must have the same type, or at least there must be an implicit conversion from the second parameter (i.e. barcode) to the first (acc).

This is necessary because reduce uses the first element of the list as the initial value of the accumulator.

In your case, the array elements are Barcode, whereas the accumulator is String. You may want to use fold instead of reduce. With fold, you are free to choose the type of the accumulator, because you explicitly specify an initial accumulator value. In your case that would be the empty string.

See also: Difference between fold and reduce in Kotlin, When to use which?

  • Related