https://kotlinlang.org logo
#announcements
Title
# announcements
r

rdgoite

07/15/2019, 2:32 PM
Hello everyone. Does anyone know how to properly protect collection type properties? What I want to do is to clone the collection into an immutable one every time
get()
is called. However, I just found out that defining something like,
Copy code
var myCollection: MutableList<String> = mutableListOf()
    private set
    get() = field.toMutableList()
is problematic because calling
this.myCollection
within the class itself seem to call the getter instead. My current alternative is to make it immutable collection and replace it every time there are changes. However, that seems to be a little more work than it should be. Any ideas?
s

Shawn

07/15/2019, 2:34 PM
the official recommendation is to have a private property that holds the mutable type and have a public property that exposes it as its read-only supertype
Copy code
private val _list = mutableListOf<Any>()
public val list: List<Any>
  private set
  get() = _list
r

rdgoite

07/15/2019, 2:50 PM
Thanks @Shawn. I forgot to mention this. My concern with this approach though is that if I were using an ORM, it’s not going to work out-of-the-box. It’s not the most inconvenient thing to add annotations to change column/field names, but, it’d still be nice if I didn’t have to.
2 Views