Klitos Kyriacou
11/29/2023, 11:11 AMinline fun <K, reified V> Map<out K, *>.filterValueIsInstance(): Map<K, V>
and it needs to be called like this:
mapOf('i' to 1, 'j' to 2, 'l' to 3L, 's' to 4.toShort()).filterValueIsInstance<Char, Int>() // == mapOf('i' to 1, 'j' to 2)
Is it possible to define it in such a way that the compiler infers what type the keys are, and just needs the target type, like this:
mapOf('i' to 1, 'j' to 2, 'l' to 3L, 's' to 4.toShort()).filterValueIsInstance<Int>() // == mapOf('i' to 1, 'j' to 2)
Javier
11/29/2023, 11:22 AMfilterValueIsInstance
which has only a type parameter.
Have you tried something like
inline fun <reified V> Map<*, *>.filterValueIsInstance(): Map<*, V>
Youssef Shoaib [MOD]
11/29/2023, 11:30 AMmyMap.filterValueIsInstance<_, Int>()
Tomer Arazy
11/30/2023, 9:09 AMinline fun <K, reified V : Any> Map<out K, *>.filterValueIsInstance(c: KClass<V>): Map<K, V>
And then call it like:
mapOf('i' to 1, 'j' to 2, 'l' to 3L, 's' to 4.toShort()).filterValueIsInstance(Int::class)
I'm not a big fan of this syntax but don't think there is a better alternative.Klitos Kyriacou
11/30/2023, 9:18 AM(c: KClass<V> = V::class)
– then the caller has a choice of syntax. 😀Youssef Shoaib [MOD]
11/30/2023, 12:50 PM_
existed for inferring type arguments:
fun main() {
mapOf('i' to 1, 'j' to 2, 'l' to 3L, 's' to 4.toShort()).filterValueIsInstance(type<Int>())
}
inline fun <K, reified V> Map<out K, *>.filterValueIsInstance(type: TypeWrapper<V> = type()): Map<K, V> = TODO()
sealed interface TypeWrapper<out T> {
companion object IMPL: TypeWrapper<Nothing>
}
fun <T> type(): TypeWrapper<T> = TypeWrapper.IMPL
Javier
11/30/2023, 12:54 PMfilterValueIsInstance<Int>()
?Youssef Shoaib [MOD]
11/30/2023, 12:56 PM