if I modify a list but at the end of the method want to return a read-only version of that same list. However because buildList uses a mutable-list as its receiver, it often makes invoking other methods in the same object a bit clumsy. Suddenly my code is full of this@… syntax.
So what I do is define something like this and use that instead:
inline fun <E> createList(
capacity: Int = 10,
builderAction: (MutableList<E>) -> Unit
): List<E> =
_buildList_(capacity) *{*
builderAction(this)
}
But of course that is not ideal. So I was wondering if there are proposals on the horizon to make buildList (or other similar scenarios) nicer to use (like would multiple-receivers also solve this use-case)?
Or perhaps people don’t mind the this@.. syntax that much?
y
Youssef Shoaib [MOD]
06/22/2023, 10:53 PM
The only situation where you'd end up needing to use this@ is if you're passing a receiver object as a parameter to a function, or if you have another receiver in scope that also happens to be a List. You shouldn't, AFAIK, need to use
this@
that often then
d
Derek Peirce
06/23/2023, 2:09 AM
You could adjust your method to be:
Copy code
inline fun <E> createList(
capacity: Int = 10,
builderAction: MutableList<E>.() -> Unit
): List<E> = buildList(capacity) {
builderAction()
}
which also allows the lambda passed into
createList
to behave more like a lambda passed to the original
buildList
.
p
Peter
06/23/2023, 7:26 AM
@Youssef Shoaib [MOD] fair point, and I guess I use it a lot in List extension functions so that might be a reason I encounter the this@ a lot.