How to typesafe reduce a Collection of Either to only Right

ssc*_*ass 5 kotlin arrow-kt

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.

pab*_*sco 6

您可以像这样映射集合:

val successes = originalSet.mapNotNull { it.orNull() }.toSet()
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要左手:

val failures = originalSet.mapNotNull { it.swap().orNull() }.toSet()
Run Code Online (Sandbox Code Playgroud)

最后toSet(),如果你想保持它作为一个可选SetmapNotNull是一个扩展功能Iterable,并总是返回List

PS:没有愚蠢的问题:)

更新: 可以避免nullables

val successes = originalSet
  .map { it.toOption() }
  .filter { it is Some }
  .toSet()
Run Code Online (Sandbox Code Playgroud)

我们可能会添加Iterable<Option<A>>.filterSomeIterable<Either<A, B>.mapAsOptions功能。

更新2:

最后一个示例返回Set<Option<Success>>。如果您想不使用结果展开结果,null则可以尝试的一种方法是Set

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

最后一个选项(意外双关语)不需要使用Option