I'm createing a generic ring buffer and I would like to use array list as internal storage for data and I'd like to allocate array list with defined capacity.
This is an example using Kotlin ArrayList:
class RingBuffer<T>(private val capacity: Int) {
private var buffer = ArrayList<T>(initialCapacity = capacity)
}
When I compile the code, this error appears:
Kotlin: None of the following functions can be called with the arguments supplied: public final fun (): kotlin.collections.ArrayList /* = java.util.ArrayList / defined in kotlin.collections.ArrayList public final fun (p0: (MutableCollection<out T!>..Collection<T!>?)): kotlin.collections.ArrayList / = java.util.ArrayList / defined in kotlin.collections.ArrayList public final fun (p0: Int): kotlin.collections.ArrayList / = java.util.ArrayList */ defined in kotlin.collections.ArrayList
I've tried to use Java ArrayList:
import java.util.ArrayList
class RingBuffer<T>(private val capacity: Int) {
private var buffer = ArrayList<T>(capacity)
}
In this case code compiles, but buffer has size=0, so array is not allocated.
So the question is how to create and then allocate ArrayList with default T values?
sizeis not the same ascapacity.sizeis 0 because the list contains nothing, but the underlying array should still be allocated with its capacity =capacity. If you really want to set a default value you can use something likeMutableList(capacity){ default }var buffer = MutableList<T?>(capacity) { null }. Do you know if it's possible to omit nullability, to make it likevar buffer = MutableList<T>(capacity) { default(T) }. For example thisdefault(T)is possible in C#, but I'm not sure if there is something similar in Kotlin or Java?