Which do you like better? :one: ```boxes.forEach {...
# codingconventions
e
Which do you like better? 1️⃣
Copy code
boxes.forEach {
    it.setOnClickListener { 
        makeColored(it) 
    }
}
2️⃣
Copy code
boxes.forEach { it.setOnClickListener { makeColored(it) } }
3️⃣ @Marc Knaup
Copy code
boxes.forEach { it.setOnClickListener(::makeColored) }
4️⃣ @ephemient
Copy code
for (box in boxes) {
    box.setOnClickListener { makeColored(it) }
}
5️⃣ @Marc Knaup @ephemient
Copy code
for (box in boxes) {
    box.setOnClickListener(::makeColored)
}
3️⃣ 17
1️⃣ 1
5️⃣ 8
m
Copy code
boxes.forEach { it.setOnClickListener(::makeColored) }
if possible 😁 In your cases 1 & 2 you’ll get a warning that you use two
it
. One parameter should be named. I’d use 2) if fits with line limit, 1) otherwise.
1
e
personally, I avoid
.forEach()
if a
for ()
loop would work. if you have a nullable chain then sure,
?.forEach()
is nice, but otherwise there's no reason.
Copy code
for (box in boxes) {
    box.setOnClickListener { makeColored(it) }
}
e
Thanks, @Marc Knaup @ephemient. I should have offered "none of the above".
I'll add your solutions if you don't mind.
m
Why would we mind? 🙂 I’d actually use @ephemient’s, but modified.
Copy code
for (box in boxes)
    box.setOnClickListener(::makeColored)
I’m not really a fan of
forEach
unless it’s part of a longer chain or necessary for some other reason.
e
@Marc Knaup I'll add that with braces. I'm a stickler for them if the statement is multiple lines.
m
Well with multiple statements you’ll need braces, yes 😄
e
You could write it:
Copy code
for (box in boxes) box.setOnClickListener(::makeColored))
and satisfy the coding guidelines as well as the compiler.
t
@Ellen Spertus that option is definitely the best
✔️ 1
g
I prefer 3️⃣ with named param:
boxes.forEach { box ->
not a fan of for/in syntax