Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build error: Type mismatch: inferred type is Unit

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>.

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading