DEV Community

Cover image for [Tiny] Kotlin list modification approach
Petr Filaretov
Petr Filaretov

Posted on

[Tiny] Kotlin list modification approach

Sometimes you need a class property of a list type with the ability to modify the list at some point later.

In Kotlin we have val/var keywords to define variables and mutable/immutable list types which gives 4 possible combinations.

val with an immutable list is not an option in our case as there is no way to modify it later.

Also, var with a mutable list doesn't make much sense here, since it leaves the ability to both assign a new list and modify the existing one.

This leaves us with two options:

  • val with mutable list
  • var with immutable list

For instance:

class ClassWithLists {
    private val mutableList: MutableList<String> = mutableListOf("1", "2", "42")
    private var immutableList: List<String> = listOf("1", "2", "42")
Enter fullscreen mode Exit fullscreen mode

Okay, but which one is the best?

As always, the answer is 42 "it depends". Both approaches are valid and have their pros and cons.

val with a mutable list looks more promising when you need to do a lot of list modifications.

On the other hand, var with an immutable list is safer. Once it is set, you can be sure it is not modified either inside or outside of the class, if you ever return it in the getter.

So, if you ask my opinion, I'd use var with an immutable list unless there are critical performance issues with this approach.

And what do you use?

Dream your code, code your dream.

Top comments (0)