https://kotlinlang.org logo
#stdlib
Title
# stdlib
m

Mark

09/07/2023, 7:51 AM
I’d like to see a compiler warning for when something like
buildString
is used but the
StringBuilder
receiver is never accessed. Same for
buildList
,
buildSet
etc. My motivation for this is that after some refactoring, I made this mistake:
Copy code
buildString {
    items.joinToString(separator = " ") {
        foo(it)
    }
}
k

Klitos Kyriacou

09/07/2023, 10:10 AM
That sounds fairly reasonable, but too specific to me. How about something more general, such as a compiler warning when the
this
receiver is not used in a lambda? That would include scope functions such as
apply
,
with
and
run
. Maybe this is the wrong channel as it's about compiler behaviour.
m

Mark

09/07/2023, 2:00 PM
I think there are often legitimate reasons to not (in general) use a receiver in a lambda, but in the examples I gave, there are no reasons not to use it. Perhaps a function that accepts a lambda can be annotated somehow to say that the receiver must be used.
j

Jeff Lockhart

09/07/2023, 5:58 PM
This seems like a similar issue as unused function return values. Sometimes it is completely valid to ignore the value. But other times it should be considered a misuse and result in a warning. Maybe a similar
@CheckReceiver
annotation for functions/lambdas makes sense?
👍 1
k

Klitos Kyriacou

09/08/2023, 8:20 AM
There are many cases when the receiver is
it
and there's no need to check it, but I can't think of any ignorable cases at the moment for a
this
receiver.
c

CLOVIS

09/08/2023, 12:38 PM
A case where it is safe to ignore the receiver:
Copy code
runBlocking {
    delay(5000)
    println("Done")
}
It's reasonable to write this code, and I'm never using the
CoroutineScope
receiver.
👍 1
k

Klitos Kyriacou

09/08/2023, 2:02 PM
Thanks, and, come to think of it, I do it all the time with KoTest.