Home > front end >  Is there a way to keep data after passing the value through constructor?
Is there a way to keep data after passing the value through constructor?

Time:05-31

I have a class that as a parameter get value with numbers. And inside that class I have a list that suppose to add those numbers every time instance of that class been created. How to make it work in Kotlin?

class MyClass internal constructor(
    private val number: Int
){

    private val listOfNumbers = mutableListOf<Int>()

    init {
        listOfNumbers.add(number)// So here it suppose to add all numbers
    }

Or maybe there is a better approach?

CodePudding user response:

Right now every instance has its own listOfNumbers.

By putting the list inside the companion object, there will be only one, shared among all instances:

    companion object {
        private val listOfNumbers = mutableListOf<Int>()
    }

CodePudding user response:

private val listOfNumbers: List<Integer> = listOf()

class Myclass {
init {
        listOfNumbers.add(number)// So here it suppose to add all numbers
    }
}

listOfnumbers will be shared, but only accessible within this file.

  • Related