Reputation: 587
Please, just keep in mind that I'm ramping up on functional programming hehe.
I have defined a Mutable list like this:
var list: MutableList<E>? = null
So, when I try to use list!!.add(E())
this throws a
kotlin.KotlinNullPointerException.
I understand that this is because I assign null to this list when I define it but a didn't get with a right solution thinking about on functional programming aspects how to solve this. Can you suggest me some code or concepts to achieve this situation.
Upvotes: 1
Views: 1266
Reputation: 263
Here is the proper declaration List.
private var mList = mutableListOf<String>()//You can change the String class to your data model
You can add values like this:
mList.add(String)//you can assign your data model class
Upvotes: 0
Reputation: 23115
You need to initialize the variable with an instance of MutableList before calling any methods on it.
list = mutableListOf<E>() // creates an empty mutable list
list!!.add(E())
If you initialize variable right at the declaration, you even don't need to declare it as nullable and var.
val list = mutableListOf<E>()
...
list.add(E())
Upvotes: 2