I'm thinking about making a contribution to simpli...
# arrow
j
I'm thinking about making a contribution to simplify converting a
NonEmptyList
to a
NonEmptySet
. Currently, I think the way to do this is:
nonEmptyList.toNonEmptySetOrNull()!!
. This isn't ideal because the
orNull
case can never happen leading to unnecessary error handling (in this case with the
!!
). Is this something people would be interested and if so which of these is preferred? Option 1: Have a
toSet()
function in the class body, so all
toSet()
calls return a a
NonEmptySet
(I like this option because the
Set
will always be "`NonEmpty`", this would change the behaviour of existing code but it wouldn't be a breaking change):
Copy code
// Sudocode implementation
class NonEmptyList<out A> {
  fun toSet(): NonEmptySet<A> = NonEmptySet(head, tail.toSet())
}

// Usage
nonEmptyList.toSet()
Option 2: Have an extension function
toNonEmptySet()
(more explicit and maybe a safer change than Option 1):
Copy code
// Implementation
fun <A> NonEmptyList<A>.toNonEmptySet(): NonEmptySet<A> = NonEmptySet(head, tail.toSet())

// Usage
nonEmptyList.toNonEmptySet()
Bonus question: Should there be an equivalent for going from
NonEmptySet
to
NonEmptyList
?
a
I think the best option here would be to have a
NonEmptyCollection
interface (maybe just with a
first()
returning
T
), make both types implement that interface, and then make
toNonEmptySet
and
toNonEmptyList
work on those
s
If the idea is only converting from a NonEmptyList, then
toNonEmptySet
sounds good to me. If you also want to add an extension on any potentially-including-nulls collection, then that'd be something like
toNonEmptySetOrNull
, IMO).
I don't think
toSet
is great, just because we already know Kotlin's sets to potentially be empty. Expressive is better, in this case, IMO.
a
this PR introduces
NonEmptyCollection
and the functions you mentioned https://github.com/arrow-kt/arrow/pull/3068
j
@Alejandro Serrano Mena Thank you for raising that. It looks good to me 👍