Hey! I have a question: What's an idiomatic way of...
# announcements
x
Hey! I have a question: What's an idiomatic way of doing this: I have a List<Foo> fooList , and Foo has properties .isA(), isB() which returns a boolean. I receive a list of properties 'state' with elements A, B, and I have to filter the list for those properties. I'm thinking of something like this:
Copy code
fooList.filter { if (state.contains('A') it.isA() else false || if (state.contains('B') it.isB() else false }
but it looks ugly
(elements can be A and B at the same time, and the state list can contain both A and B)
a
What do you wan't to have in the end?
x
a filtered fooList based on the conditions set on the state basically
j
Something so maybe?
a
you could store the filtering function if a variable:
Copy code
val f = if (state.contains("A")) Foo::isA else Foo::isB
list.filter(f)
x
i think i didnt explain myself properly, here's a better example:
Copy code
funFilterByState(state: List<String>){
val test = ListOf(Foo("a", null), Foo (null, "b"))
return test.filter(if (state.contains("a")) it.isA() else false || if (state.contains("b") it.isB() else false)
}

data class Foo(val f: String?, val g: String?){
val isA: Boolean = f != null
val isB: Bolean = g != null}
@alightgoesout i like that idea but doing Foo::isA casts it to any 🤔
m
Copy code
state.contains('a') && isA || state.contains('b') && isB
operator precedence and short circuiting will always result in your desired result here.
if(x) a else false === x && a
x
that's exactly it @Michael de Kaste, thank you! looks pretty and is functional
a
surely you want to pull the check of state out of the filter? that is
fooList.filter(if (state.contains('A')) { it.isA() } else { it.isB() })