Reputation: 381
Kotlin:
take
and
takeLast
all accept Int
values but the Lists on which they are being invoked have sizes greater an Int
can handle.
How do I deal with this situation?
Upvotes: 0
Views: 266
Reputation: 23079
Kotlin defines a version of takelast
that works on a LongArray
:
fun LongArray.takeLast(n: Int): List<Long>
The limitation on the input parameter is only one of how many items you can "take" from the target Array. Is this really your problem? Do you really want to take more than Int.MAX_VALUE items from the target array? If so, then you can't use this function, as there is no version of it that accepts a Long
for the number of values to take from the array.
What are the values in the Array you're talking about? If they're Int
s, you're talking about an 8GB transfer. And you have to have at least that much in the Array to copy, so you're talking about more than 16GB of memory space for the source and destination of this operation. I can't believe that this is what we're talking about. Even if they're Byte values, a 2GB transfer done this way in memory doesn't make any sense to me. What is your use case?
Upvotes: 0
Reputation: 14255
At least for take
nothing stops you from creating your own extension function:
fun <T> Iterable<T>.take(n: Long): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0L) return emptyList()
if (this is Collection<T>) {
if (n >= size) return toList()
if (n == 1L) return listOf(first())
}
var count = 0L
val list = ArrayList<T>()
for (item in this) {
list.add(item)
if (++count == n)
break
}
return list
}
takeLast
is a bit more complicated, because lists only use Int
for several other things (like get
or size
) as well. But you can always look at the source code and adapt.
Upvotes: 2