0

I want to implement stack data structure using kotlin. I want to use generic array so as to create stack of any datatype. I am not sure how to initialize the array properly. It shows different kind of errors everytime. Also cannot figure out how to use List<T>. Any kind of help will be appreciated.

class StackADT<ANY>(var capacity: Int) {

    private var top = -1
    private val stack:  (generic type array)//NEED TO INITIALIZE PROPERLY HERE 

    fun push(element: ANY) {
        if (top == capacity)
            throw Exception("Overflow occurred in stack!!")
        stack[++top] = element
    }
    ....

Sagar Jogadia
  • 1,330
  • 1
  • 16
  • 25

1 Answers1

0
class StackADT<T>(var capacity: Int) {

    private var top = -1
    private val stack: ArrayList<T> = ArrayList(capacity)

    fun push(element: T) {
        if (top == capacity)
            throw Exception("Overflow occurred in stack!!")
        top++
        stack.add(element)
    }
    ...

You can test here: Kotlin Playground

Another way:

var stack = arrayOfNulls<Any?>(capacity) as Array<T>
JavierSegoviaCordoba
  • 6,531
  • 9
  • 37
  • 51