I have a const object In it I have a const list
I try to initialize the list in the constructor ... but any call to "add" (in the ctor) results in a runtime error : "list is readonly"
Can I do it a different way ... maybe create a new list in the ctor that I add to, and then assign it to my const list
Would that be the proper way to do it ?
The key thing to remember is that when you assign a list to a const field, that is when it is made immutable:
// this code this.constField = list // always gets translated into this this.constField = list?.toImmutable
So the best way to do it is built up your list via a local variable, then assign to the field once you are ready to lock it down.
Cool, that's what I did.
One thing I don't like is that it's a runtime error(don't like those), maybe the compiler could warn about this ?
Login or Signup to reply.
tcolar Wed 26 May 2010
I have a const object In it I have a const list
I try to initialize the list in the constructor ... but any call to "add" (in the ctor) results in a runtime error : "list is readonly"
Can I do it a different way ... maybe create a new list in the ctor that I add to, and then assign it to my const list
Would that be the proper way to do it ?
brian Wed 26 May 2010
The key thing to remember is that when you assign a list to a const field, that is when it is made immutable:
So the best way to do it is built up your list via a local variable, then assign to the field once you are ready to lock it down.
tcolar Wed 26 May 2010
Cool, that's what I did.
tcolar Wed 26 May 2010
One thing I don't like is that it's a runtime error(don't like those), maybe the compiler could warn about this ?