https://kotlinlang.org logo
Title
z

zain

02/15/2022, 9:53 AM
Can we do a conditional chain in Kotlin? or ignore it and go to the next operator?
private fun simulateFixtures(list: List<List<Team>>) = list.map { fixture ->
    fixture.toList().random()
}.shuffled().chunked(2)
s

Sam

02/15/2022, 10:11 AM
Can you give a bit more detail? Not sure what your example code is trying to convey
⬆️ 2
My first thought on reading your message is it sounds like a job for Arrow though
s

Sam

02/15/2022, 10:24 AM
based on that StackOverflow thread, I would say the canonical solution is something like:
foo.let {
    if (somePredicate) it.doSomething() else it
}
Does that match what you're trying to do? Are you just looking for a shorter way to write it?
👍 1
z

zain

02/15/2022, 10:25 AM
That matches
s

Sam

02/15/2022, 10:27 AM
I think you'll struggle to find a more concise and readable way to write it than
let
+ `if`/`else`
👍 1
It is a bit wordy though 😞
The
else it
on the end is particularly cumbersome
j

Joffrey

02/15/2022, 10:39 AM
What part do you want to run conditionally? All operations look general enough to be done in one go. If you have only 1 fixture in the list passed as argument, you wouldn't even need to call this method, because you would just pick the winner and the result would not be a list or 2-element lists anyway
Also, you have a
List<List<Team>>
, you don't need
toList()
before using
random()
on an element. It's already a list, and you don't need a copy just to choose a random element out of it.
m

Michael de Kaste

02/15/2022, 10:45 AM
@Sam well, the kotlin devs have explicitely not added the ternary operator:
condition ? onTrue : onFalse