https://kotlinlang.org logo
Title
o

oday

08/14/2022, 6:55 PM
is there a shorter way of writing this?
val names = ArrayListQueue<String>()

    map["you"]?.forEach{
        names.enqueue(it)
    }
I was thinking like
map["you"].forEach(::names.enqueue)
?
l

Landry Norris

08/14/2022, 7:07 PM
Try names::enqueue I think that's the syntax for a method reference with an object.
o

oday

08/14/2022, 7:08 PM
great! yes that’s it!
thanks
y

Youssef Shoaib [MOD]

08/14/2022, 7:38 PM
Pretty sure btw that if you Alt-Enter on the lambda body, IntelliJ should suggest "convert lambda body to function reference"
b

Ben Edwards

08/14/2022, 9:59 PM
IMHO trying to create short 'clever' code reduces readability, maintainability and makes it more difficult to debug. Just saying 🙂.
Although it's a fun exercise.
m

Michael de Kaste

08/15/2022, 8:24 AM
well tbf, this is just conversion to function reference, which isn't really shortening anything. besides, in my team, we have function reference as a 'best practice' (implicitely typing the call site is 'safer')
y

Youssef Shoaib [MOD]

08/15/2022, 9:46 AM
With the risk of going off topic here, I think that code-shortening can be a good exercise in improving readability by reducing visual noise and duplication. In this case I think it makes it slightly clearer that each item is enqueued directly, with no extra logic whatsoever. Code shortening is in general a good way to explore an alternative representation of the code, which could turn out to be more readable and can help signify that this piece of code isn't super important or doesn't have any complex logic (I usually find that short code = simple logic when reading it)