Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Type inference failed. Expected type mismatch: inferred type is MutableList<Long?> but MutableCollection<Long> was expected

I'm attempting to create a MutableList using kotlin but I'm getting an error stating:

Type inference failed. Expected type mismatch: inferred type is MutableList but MutableCollection was expected

...and I'm not sure how to convert the MutableList to a MutableCollection.

I've tried using:

.toMutableList().toCollection()

but it's looking for a destination - and I'm not sure what to do.

Code Snippet:

data class HrmSearchResult(
    var rssi: Short?,
    var adjustRssi: Short?,
    var timeout: Int,
    var serialNumber: Long?,
    var isIn: Boolean,
    var countIn: Int
)

private val hashMapHrm = ConcurrentHashMap<Long?, HrmSearchResult>()

val hrmDeviceList: MutableCollection<Long>
    get() = try {
        if (hashMapHrm.elements().toList().none { it.isIn}) {
            //if there are no member in range, then return empty list
            arrayListOf()
        } else {
            hashMapHrm.elements()
                .toList()
                .filter { it.isIn }
                .sortedByDescending { it.adjustRssi }
                .map { it.serialNumber }
                .toMutableList().toCollection()
        }
    } catch (ex: Exception) {
        AppLog.e(
            LOG, "Problem when get devices " +
                    "return empty list: ${ex.localizedMessage}"
        )
        arrayListOf()
    }

Any suggestions are appreciated.

like image 829
user13125638 Avatar asked Mar 26 '20 00:03

user13125638


1 Answers

The problem is the nullability, not the collection type, i.e. that you are creating a List<Long?> where a List<Long> is expected.

You can reproduce your error message (inferred type is MutableList<Long?> but MutableCollection<Long> was expected) minimally with this:

val foo: MutableCollection<Long> =
    listOf(1L, 2, 3, 4, null)
        .toMutableList()

And you can fix it by inserting .filterNotNull() to remove potential nulls, and convert a List<T?> to a List<T>:

val foo: MutableCollection<Long> =
    listOf(1L, 2, 3, 4, null)
        .filterNotNull()
        .toMutableList()

(So your .toCollection() call is actually not needed and can be dropped)

Some other notes specific to your code:

You probably want to use .values over .elements.toList(), and map { }.filterNotNull() can be combined into mapNotNull, so in summary, you probably want to write your chain as

hashMapHrm.values
    .filter { it.isIn }
    .sortedByDescending { it.adjustRssi }
    .mapNotNull { it.serialNumber }
    .toMutableList()
like image 83
Erik Vesteraas Avatar answered Nov 15 '22 09:11

Erik Vesteraas