Okay, so to try to learn the kotlin language, I am trying to implement a heap.
class Heap <T : Comparable<T>>(private var heap: Array<T>, private var size: Int){
I am having some difficulties with how the nullable types behave. In the beginning I gave a array of elements, but I started having difficulties when I wanted to allocate more elements
private fun increaseSize(){
if(size == heap.size){
//okay this is garbage
var enlargedHeap = arrayOfNulls<Comparable<*>>(heap.size * 2) as Array<T>
System.arraycopy(heap, 0, enlargedHeap, 0, size)
heap = enlargedHeap
}
}
So here I am guessing I am changing the heap from Array<T> to Array<T?> which makes sense. So I changed the constructor as well, to take Array<T?> and it suggests some pretty interesting things wherever I try to access heap[x]
else heap[pos1].compareTo(heap[pos2]) < 0
to
else heap[pos2]?.let { heap[pos1]?.compareTo(it) }!! < 0
then I looked at a tooltip stating that arrayOfNulls<Comparable<*>>(heap.size * 2) as Array<T> returned Array<T>
But when doing the arrayOfNulls it indeed returns an array with null values. However I get an error if I try to heap[x] = null
stating
Null cannot be a value of non-null type T
If I change the constructor to take a Array<T?>, then input arrays have to explicitly nullable too.
Which I fixed with
class Heap <T : Comparable<T>>{
private var heap: Array<T?>
private var size = 0
constructor(heap: Array<T>, size){
this.heap = heap as Array<T?>
this.size = size
}
But now it does not accept arrays that has null values when I try to instantiate it with an array with nullable values
var arr = arrayOfNulls<String>(9)
var heap = Heap(arr, arr.size-1)
So now I need two constructors? What is going on
Type mismatch. Required: Comparable Found:String?
Even with Àrray<T?> there is errors with the compareTo's not accepting nullable values.
Even with checks it still gives an error
return if(pos2 > size || (heap[pos1] == null || heap[pos2] == null)) false
else heap[pos1].compareTo(heap[pos2]) < 0
Type mismatch. Required:T Found: T?
How do I allow the array to contain null values?
Hopefully without making Array<T> nullable since it breaks the compareTo's and multiple constructors seems like bad design.