0

I have something like:

List(CustomType(NonEmptyList(Error(Bar(b,4,c)))), CustomType(NonEmptyList(Error(Bar(a,6,z)))))

I'm trying to flatten it to get:

 List(Error(Bar(b,4,c)), Error(Bar(a,6,z)))

I tried using flatten but I run into an issue with implicit not being found and I can't find a way to write an implicit.

I apologize if a similar question has been asked before but I couldn't find answers to solve this issue.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
NoName
  • 1,509
  • 2
  • 20
  • 36
  • It would be good if you could provide a simple definition of `CustomType` - Also, it seems you are pretty new to **Scala** _(because you should know why `flatten` didn't work)_, it is not really recommended to use something somewhat advanced like **cats** if you are not familiar with the language first. Have you read _"Scala with Cats"_? If not, I recommend it to you. – Luis Miguel Mejía Suárez Jan 29 '21 at 12:25

2 Answers2

2

If .flatten can't find the implicit code to flatten your collection, you can often supply it yourself explicitly.

import cats.data.NonEmptyList
case class Bar(a:Char,b:Int,c:Char)
case class Error(bar: Bar)
case class CustomType(value: NonEmptyList[Error])

List(CustomType(NonEmptyList(Error(Bar('b',4,'c')),Nil))
   , CustomType(NonEmptyList(Error(Bar('a',6,'z')),Nil)))
  .flatten(_.value.toList)
//res0: List[Error] = List(Error(Bar(b,4,c)), Error(Bar(a,6,z)))

You'll notice that I had to make a few assumptions about your example code. (It helps if you post code that compiles.)

jwvh
  • 50,871
  • 7
  • 38
  • 64
1

For flatten to work, you should strip CustomType and convert NonEmptyLists to Lists. The method to deal with CustomType depends on what exactly the CustomType is.

If the CustomType is cats.data.Validated, then you should check this answer: How to flatten a sequence of cats' ValidatedNel values

If the CustomType is Left and you have a List[Either[NonEmptyList[Error], T]], then you can flatten it with:

import cats.implicits._

list.collectFold {
  case Left(nel) => nel.toList
}

The same approach can be used if CustomType is one case of some sealed trait.

If the custom type is something simple like case class CustomType(errors: NonEmptyList[Error]), then you can simply use flatMap:

list.flatMap(_.errors.toList)
Kolmar
  • 14,086
  • 1
  • 22
  • 25