为何调用TypeConverter返回的List的add方法提示‘Unresolved reference: add’?
The Problem
You’ve built a TypeConverter to turn a string into a list of Longs, but when you try to call add() on the returned list, you hit an "Unresolved reference: add" error. Here’s your code for context:
Your TypeConverter implementation:
TypeConverter { fun stringToListLong(text: String): List<Long> { val listLong = mutableListOf<Long>() val listString = text.split(",").map { it.trim() } listString.forEach { listLong.add(it.toLong()) } return listLong } }
The usage that fails:
val someString = "something" var ids = TypeConverter.stringToListLong(someString) ids.add(123L) // Error: Unresolved reference: add
The Root Cause
In Kotlin, List<T> is an immutable (read-only) collection interface. It only exposes methods for reading elements (like get(), size, or contains())—modification methods such as add() or remove() are not part of its contract.
Even though you’re creating a MutableList<Long> with mutableListOf() inside your function, you’re returning it as a List<Long>. This upcasts the mutable list to its read-only supertype, so the caller only sees the restricted, read-only interface.
Fixes
There are two simple ways to fix this:
1. Change the function’s return type to MutableList<Long>
Update your TypeConverter to return the mutable list directly, so the caller receives a collection that supports modifications:
TypeConverter { fun stringToListLong(text: String): MutableList<Long> { val listLong = mutableListOf<Long>() val listString = text.split(",").map { it.trim() } listString.forEach { listLong.add(it.toLong()) } return listLong } }
Now you can call add() on the returned list without any errors.
2. Convert the read-only List to a MutableList at the call site
If you don’t want to modify the TypeConverter’s return type, you can convert the result to a mutable list when you use it:
val someString = "something" var ids = TypeConverter.stringToListLong(someString).toMutableList() ids.add(123L) // Works perfectly now!
The toMutableList() function creates a new mutable copy of the read-only list, which you can then modify freely.
Bonus: Simplify Your TypeConverter Code
As a side tip, you can streamline your function using Kotlin’s built-in collection functions instead of manual looping:
fun stringToListLong(text: String): List<Long> { return text.split(",") .map { it.trim() } .filter { it.isNotEmpty() } // Optional: Skip empty strings to avoid conversion errors .map { it.toLong() } }
This achieves the same result in a more concise way. If you need a mutable list, just change the return type to MutableList<Long> and append .toMutableList() at the end of the chain.
内容的提问来源于stack exchange,提问作者Viktor

