https://kotlinlang.org logo
#random
Title
# random
d

Davide Giuseppe Farella

11/03/2023, 4:19 PM
Hey folks, I was wondering if there is any Keep or discussion about something that I would call “partial inference on type parameters” Example:
Copy code
interface 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:
Copy code
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:
Copy code
class A
class B

val list: List<A>
list.filterIsInstance<B>() // 💥
y

Youssef Shoaib [MOD]

11/03/2023, 5:37 PM
Well, you can do
Child().<_, Int>()
but it's definitely ugly. I wish there was a way to specify that certain type params should always be inferred.
d

Davide Giuseppe Farella

11/03/2023, 5:38 PM
Yes, indeed I was wondering if there is a Keep, a feature request, or whatever related to that 🙂
y

Youssef Shoaib [MOD]

11/03/2023, 5:39 PM
You might get more interest/info on #language-evolution
d

Davide Giuseppe Farella

11/03/2023, 5:40 PM
Thank you! I’ll move it there then 🙂
h

hfhbd

11/03/2023, 6:22 PM
This is the reason I never use filterIsInstance but a plain mapNotNull. I ran into this error a few times too and it always took a while why the resulting list was empty.
3 Views