Bart Kleijngeld
02/09/2022, 3:40 PMimport java.io.File
private fun Format(filename: String): Format? {
// Never mind the implementation here.
}
fun readFiles(files: Sequence<File>): Map<Format, List<Reader>> =
files
.groupBy { getFormat(it.toString()) }
.filterKeys { it != null }
.mapValues { it.value.map { f -> f.reader() } } // ERROR: Type mismatch: inferred type is Format? but Format was expected
Bart Kleijngeld
02/09/2022, 3:41 PMfilterKeys
gets rid of all the entries with null
valued keys, doesn't it?
Is the issue perhaps that this is not known at compile time?Sam
02/09/2022, 3:41 PMJoffrey
02/09/2022, 3:41 PMIs the issue perhaps that this is not known at compile time?This
Bart Kleijngeld
02/09/2022, 3:42 PMJoffrey
02/09/2022, 3:42 PMfilterNotNull
which do enforce the nullability in their return type, so it's known at compile time. I don't know if there are equivalents on maps thoughBart Kleijngeld
02/09/2022, 3:43 PMJacob
02/09/2022, 4:10 PMfiles
.mapNotNull { file ->
getFormat(file.toString())?.let { it to file.reader() }
}.groupBy { it.first }
Bart Kleijngeld
02/09/2022, 4:21 PMfilterNotNullKeys
extension function on maps.Michael de Kaste
02/09/2022, 4:24 PMMichael de Kaste
02/09/2022, 4:24 PMfiles
.mapNotNull { file -> getFormat(file.toString())?.let { it to file.reader() } }
.groupBy({ it.first }, { it.second })
Joffrey
02/09/2022, 4:24 PMgroupBy
that also has a valueTransform
so you get the correct valuesJoffrey
02/09/2022, 4:25 PMBart Kleijngeld
02/09/2022, 4:26 PMMichael de Kaste
02/09/2022, 4:27 PMephemient
02/09/2022, 8:33 PM@Suppress("UNCHECKED_CAST")
fun <K, V : Any> Map<K, V?>.filterNotNullValues(): Map<K, V> = filterValues { it != null } as Map<K, V>
ephemient
02/09/2022, 8:36 PMBart Kleijngeld
02/10/2022, 6:39 AM