Reputation: 23513
I am trying to create an ArrayList
in a class, like so:
class ConvertableTests : BaseTest(){
var categories = ArrayList<String>()
categories.add('a') <---- //Expecting member declaration error here
inner class ConvertableClass : Convertible...
Why I can't add objects to my array list after I initialize the list?
Upvotes: 2
Views: 696
Reputation: 3349
You can add items into the list after you initialize the list if you aren't doing so at the root scope of the class. Same as if you would have tried to do the same thing in Java.
i.e.
//this won't work, like you just found out
class Example {
var categories = ArrayList<String>()
categories.add("a") // this isn't inside a function or an `init` block
}
You need to put it inside of a function or an init
block
fun functionExample() {
var categories = ArrayList<String>()
categories.add("a") // This would work fine
}
or
class Example {
var categories = ArrayList<String>()
init {
categories.add("a")
}
}
To elaborate on Sergey's example of the apply
and why that works if you don't do it inside of a function or an init
class Example {
var categories = ArrayList<String>().apply {
add("a")
}
}
The kotlin compiler is performing an optimization and it's actually treating this as if you were putting it into an init
block. If you decompile this and see what's happening, it's actually doing this
/// This is what it compiles back up to in Java
public Example() {
ArrayList var8 = new ArrayList();
var8.add("a");
this.category = var8;
}
Which is the same thing that happens when you use the init
block.
Hope that helps!
Upvotes: 4
Reputation: 30765
You can use init
block to initialize array:
class ConvertableTests : BaseTest() {
var categories = ArrayList<String>()
init {
categories.add("a")
}
// ...
}
Or apply
extension function:
var categories = ArrayList<String>().apply {
add("a")
}
Also you should use double quotes "
to add a String
:
var categories = ArrayList<String>()
categories.add("a")
Single quotes are used for Char
s:
var categories = ArrayList<Char>()
categories.add('a')
Upvotes: 3