Is there any way to pass a `Collection<I>` (not re...
# getting-started
d
Is there any way to pass a
Collection<I>
(not reified) with a spread operator to a vararg function? It seems like toTypedArray() won't work without reified...
y
Does your vararg function accept a non-reified generic or
Any?
? if so, I think you can simply upcast your
Collection
to
Collection<Any?>
and then do
toTypedArray()
d
It's a non-reified generic, I'm trying to use Lettuce's (Java)
RedisFuture<Long> del(K... keys);
And I need to implement
override suspend fun expire(ids: Collection<I>)
(I == K)
y
I think just typing it as
Any?
should work then
p
Copy code
fun <T> del(vararg values: T) {
    values.forEach { 
        println("deleting: $it")
    }
}

fun <T> expire(ids: Collection<T>) {
    del(*ids.toTypedArray<Any?>())
}

fun main() {
    expire(listOf("hello", "world"))
}
d
Type mismatch. Required: I! Found: Array<Any?>
p
yeah - I just realised your
K
is bound by the Lettuce interface and cannot be lifted to Any?.
d
It's a real pity they don't even have an overload taking in a collection...
I do need to pass the KClasses or something into my class for Kotlinx serialization though, does that help?
And for the key and for the value
p
an option would be to take the potentially unsafe cast and use
*(ids.toTypedArray<Any?>() as Array<I>)
assuming you can ensure that I == K
you know that
ids.toTypedArray<Any?>()
will only contain `I`s - so you can safely cast it.
d
I guess that's assured by my function signature, no?
Copy code
override suspend fun expire(ids: Collection<I>) {
        connection.async().del(*(ids.toTypedArray<Any?>() as Array<I>)).await()
    }
p
yup, assuming async() returns an instance of the interface such that the
K
type-arg is your
I
from that context then the
del
call is fine (the array casting is fine by way of your signature)
d
Copy code
val connection: StatefulRedisConnection<I, V> =
        redis.connect(JsonCodec(Json, keySerializer, valueSerializer))
👍 1
Thanks!
r
Looks like there's an open issue for it, but it's on hold till collection literals are done: https://youtrack.jetbrains.com/issue/KT-12663/Spread-operator-for-Iterable-Collection-in-varargs
👍🏼 1