is there a function to split a collection into two...
# getting-started
e
is there a function to split a collection into two sub collections by a predicate?
Copy code
val unsInfos = intTypeInfo.filter { it.type[0] == 'U' }
val signInfos = intTypeInfo.filter { it.type[0] != 'U' }
ie
Copy code
val (unsInfos, signInfos) = intTypeInfo.x { it.type[0] == 'U' }
..
partition
!
r
I was just about to say that. 🙂
e
I was searching by
split
or
divide
, then by defining the type, at the end I managed to find the answer on Google
r
Yeah, that can sometimes be the hardest part about finding what you're looking for. There are so many synonyms for most actions, it's hard to find the right one.
e
Destructuring declarations are only allowed for local variables/values
😕
r
Is there a reason you index
type
in the scope where you're filtering/partitioning? Is
type
a sub-array in the object?
e
it's a list of numeric types
Copy code
val intTypeInfo = listOf(
    TypeInfo("Byte", "b"),
where
Copy code
data class TypeInfo(val type: String, val extension: String)
a quick way to filter out unsigned types and viceversa
r
OK, I see.
I'm not sure what that "Destructuring declarations" message is about. Is that a compiler error the IDE is giving you? How are you declaring
intTypeInfo
?
e
you cant
val (unsInfos, signInfos)
at top level
r
Oh, I see. This isn't inside of a function?
e
no
r
OK
You might be able to declare
unsInfo
and
signInfos
as vals at the top level, then do your
partition
call in the
init
block.
e
it's all top level, I don't have an
init
r
Oh, OK.
Maybe make it an extension function on
List<TypeInfo>
?
e
I'm gonna bite the bullet and duplicate code as the first snippet
r
OK
k
To avoid iterating your list twice, if you don't mind polluting the current file, you can do:
Copy code
private val pair = ...partition(...)
val unsInfos = pair.first
val signInfos = pair.second
âž• 3
e
(also holding onto the pair object for as long as the object lives)
âž• 1