Should we avoid `@UnsafeVariance`? I'm trying to ...
# library-development
d
Should we avoid
@UnsafeVariance
? I'm trying to decide the best approach for the Immutable Arrays library. Immutable Arrays are covariant so you can pass an
ImmutableArray<Employee>
to functions that expect
ImmutableArray<Person>
when
Employee
extends
Person
. With
ImmutableArray<T>
, most operations produce
T
but there are a handful that consume `T`: •
contains(element: T)
indexOf(element: T)
lastIndexOf(element: T)
getOrElse(index: Int, default: (Int) -> T)
There are also a couple that might be more dangerous for ensuring type safety if
T
was declared as `in T`: •
plus(element: T)
// creates a new Immutable Array with the element appended •
plus(elements: ImmutableArray<T>)
// creates a new Immutable Array with the elements appended Attempting to add any of these methods results in an error:
Type parameter 'T' is declared as 'out' but occurs in 'in' position
I worked around this problem by turning these methods into extension functions which utilize allowed methods:
Copy code
fun <T> ImmutableArray<T>.contains(element: T): Boolean {
    return any { it == element }
}

fun <T> ImmutableArray<T>.indexOf(element: T): Int {
    forEachIndexed { index, value -> if (value == element) return index }
    return -1
}
//...
The extension functions require additional imports (which IntelliJ nicely auto-suggests) so I'm wondering whether to continue with the extension function approach for these handful of operations or whether to make them regular methods by using
@UnsafeVariance
to avoid the imports. Searching in YouTrack, I get the impression that Kotlin is moving away from using
@UnsafeVariance
but I'm not sure if I'm interpreting that correctly: • https://youtrack.jetbrains.com/issue/KT-57603/Prohibit-using-UnsafeVariance-for-invariant-type-parameterhttps://youtrack.jetbrains.com/issue/KTLC-72/K2-Stop-relying-on-the-presence-of-UnsafeVariance-using-for-contravariant-parameters I noticed that kotlinx immutable collections use
@UnsafeVariance
for their persistent abilities. Does anyone know the official direction that the Kotlin team is planning for
@UnsafeVariance
or what the officially recommended approach is for dealing with these types of variance scenarios?
👀 1
d
UPD: removed my message to avoid misleading, as I believe I said some nonsense.