Davide Giuseppe Farella
11/03/2023, 4:19 PMinterface Parent
class Child : Parent
fun <P : Parent, R> P.foo(): R? {
return this as? R
}
fun test() {
// First type param is completely unnecessary and redundant
Child().foo<Child, Int>()
// This compiles too, as all the types are inferred. Everything or nothing :)
val i: Int? = Child().foo()
}
Common scenario:
From stdlib:
public inline fun <reified R> Iterable<*>.filterIsInstance(): List<@kotlin.internal.NoInfer R> {
return filterIsInstanceTo(ArrayList<R>())
There is a big problem here: to avoid declaring two params, we have unbounded R
.
I recently did a small refactor of untested code (ye, untested code is already bad per se..), but it was just a matter of changing A
with B
in a few places, and what could possibly go wrong? Kotlin is a strongly typed language, right?
But probably not in this case:
class A
class B
val list: List<A>
list.filterIsInstance<B>() // 💥
Youssef Shoaib [MOD]
11/03/2023, 5:37 PMChild().<_, Int>()
but it's definitely ugly. I wish there was a way to specify that certain type params should always be inferred.Davide Giuseppe Farella
11/03/2023, 5:38 PMYoussef Shoaib [MOD]
11/03/2023, 5:39 PMDavide Giuseppe Farella
11/03/2023, 5:40 PMhfhbd
11/03/2023, 6:22 PM