Search code examples
scalascala-cats

Convert Set to cats.data.NonEmptySet?


Is there an extension method in cats for the standard Set which converts it to Option[cats.data.NonEmptySet]?


Solution

  • Not for scala.collection.immutable.Set, but for SortedSet:

    scala> import cats.syntax.set._
    import cats.syntax.set._
    
    scala> import scala.collection.immutable.SortedSet
    import scala.collection.immutable.SortedSet
    
    scala> SortedSet(1, 2, 3).toNes
    res0: Option[cats.data.NonEmptySet[Int]] = Some(TreeSet(1, 2, 3))
    

    You can of course convert an ordinary Set:

    scala> Set(1, 2, 3).to[SortedSet].toNes
    res1: Option[cats.data.NonEmptySet[Int]] = Some(TreeSet(1, 2, 3))
    

    Cats's NonEmptySet isn't built on Set (and Cats doesn't provide syntax for Set) because Set relies on universal equality to determine what counts as uniqueness for its elements. SortedSet on the other hand requires a scala.math.Ordering instance, which makes it more aligned with the design principles followed in Cats (see e.g. this issue for more discussion).