https://kotlinlang.org logo
#getting-started
Title
# getting-started
e

elect

09/15/2023, 4:39 PM
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

Russell Stewart

09/15/2023, 4:42 PM
I was just about to say that. 🙂
e

elect

09/15/2023, 4:43 PM
I was searching by
split
or
divide
, then by defining the type, at the end I managed to find the answer on Google
r

Russell Stewart

09/15/2023, 4:44 PM
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

elect

09/15/2023, 4:45 PM
Destructuring declarations are only allowed for local variables/values
😕
r

Russell Stewart

09/15/2023, 4:47 PM
Is there a reason you index
type
in the scope where you're filtering/partitioning? Is
type
a sub-array in the object?
e

elect

09/15/2023, 4:48 PM
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

Russell Stewart

09/15/2023, 4:49 PM
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

elect

09/15/2023, 4:52 PM
you cant
val (unsInfos, signInfos)
at top level
r

Russell Stewart

09/15/2023, 4:52 PM
Oh, I see. This isn't inside of a function?
e

elect

09/15/2023, 4:52 PM
no
r

Russell Stewart

09/15/2023, 4:52 PM
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

elect

09/15/2023, 4:54 PM
it's all top level, I don't have an
init
r

Russell Stewart

09/15/2023, 4:54 PM
Oh, OK.
Maybe make it an extension function on
List<TypeInfo>
?
e

elect

09/15/2023, 4:55 PM
I'm gonna bite the bullet and duplicate code as the first snippet
r

Russell Stewart

09/15/2023, 4:57 PM
OK
k

Klitos Kyriacou

09/15/2023, 5:03 PM
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

ephemient

09/15/2023, 5:24 PM
(also holding onto the pair object for as long as the object lives)
1