Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
How to typesafe reduce a Collection of Either to only Right

Maybe a stupid question but I just don't get it.

I have a Set<Either<Failure, Success>> and want to output a Set<Success> with Arrow-kt.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can map the set like this for right:

val successes = originalSet.mapNotNull { it.orNull() }.toSet()

or if you want the lefts:

val failures = originalSet.mapNotNull { it.swap().orNull() }.toSet()

The final toSet() is optional if you want to keep it as a Set as mapNotNull is an extension function on Iterable and always returns a List

PS: No stupid questions :)

Update: It can be done avoiding nullables:

val successes = originalSet
  .map { it.toOption() }
  .filter { it is Some }
  .toSet()

We could potentially add Iterable<Option<A>>.filterSome and Iterable<Either<A, B>.mapAsOptions functions.

Update 2:

That last example returns a Set<Option<Success>>. If you want to unwrap the results without using null then one thing you can try is to fold the Set:

val successes = originalSet
  .fold(emptySet<Success>()) { acc, item -> 
    item.fold({ acc }, { acc + it })
  }

This last option (unintended pun) doesn't require the use of Option.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda