Bram
Bram

Reputation: 3

I can't initialize my array (MutableList) within a class in Android

I just started with Kotlin and Android studio. When in the MainActivity.kt I do the following ...

var tafels: MutableList<MutableList<Int>> = java.util.ArrayList()
tafels.add(mutableListOf<Int>(2, 2, 4))

... everything works fine. I can add elements to this ArrayList, as shown.

When I try to do the same in a new file, in a class I created, however, the code assist doesn't recognise tafel when I type it in, and therefore no suggestions come after I type tafels:

class TafelsSommen(){

    var tafels: MutableList<MutableList<Int>> = java.util.ArrayList()            
    tafels.add(mutableListOf<Int>(2, 2, 4))
}

Why can't I add elements to tafels inside class TafelsSommen?

Upvotes: 0

Views: 972

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81899

First of all, you could make use of standard lib functions for creating your lists. The following is type safe whereas yours isn’t because the ArrayList did not specify its type parameter.

val tafels: MutableList<MutableList<Int>> = mutableListOf(mutableListOf(2, 2, 4))

You're trying to invoke code, here adding an element to list, in the class body. This does not work. Wrap it into an init block or add it to the property declaration:

class TafelsSommen() {
    val tafels: MutableList<MutableList<Int>> = mutableListOf(mutableListOf())

    init {
        tafels.add(mutableListOf(2, 2, 4))
    }
}

Again, here’s how a class can be structured:

“Classes can contain”:

  • Constructors and initializer blocks
  • Functions
  • Properties
  • Nested and Inner Classes
  • Object Declarations

No statement like yours allowed.

Upvotes: 2

Related Questions