【问题标题】:How do I flatten a nested NEL of custom type in Scala?如何在 Scala 中展平自定义类型的嵌套 NEL?
【发布时间】:2021-01-29 04:39:02
【问题描述】:

我有类似的东西:

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

我正在尝试将其展平以获得:

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

我尝试使用 flatten,但遇到了一个未找到隐式的问题,并且我找不到编写隐式的方法。

如果之前有人问过类似的问题,但我找不到解决此问题的答案,我深表歉意。

【问题讨论】:

  • 如果你能提供一个简单的CustomType 定义就好了——另外,你似乎对Scala 很陌生(因为你应该知道为什么flatten 没用),如果你不熟悉语言,不建议使用像 cats 这样的高级工具。你读过“Scala with Cats”吗?如果没有,我推荐给你。

标签: scala scala-cats


【解决方案1】:

如果.flatten 找不到隐式代码来展平您的集合,您通常可以自己显式提供。

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)))

您会注意到我不得不对您的示例代码做出一些假设。 (如果您发布可编译的代码,这会有所帮助。)

【讨论】:

    【解决方案2】:

    要使flatten 工作,您应该剥离CustomType 并将NonEmptyLists 转换为Lists。处理CustomType的方法取决于CustomType到底是什么。

    如果CustomTypecats.data.Validated,那么你应该检查这个答案:How to flatten a sequence of cats' ValidatedNel values

    如果 CustomTypeLeft 并且您有 List[Either[NonEmptyList[Error], T]],那么您可以将其展平:

    import cats.implicits._
    
    list.collectFold {
      case Left(nel) => nel.toList
    }
    

    如果CustomType 是某些sealed trait 的一种情况,则可以使用相同的方法。

    如果自定义类型很简单,比如case class CustomType(errors: NonEmptyList[Error]),那么你可以简单地使用flatMap

    list.flatMap(_.errors.toList)
    

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 1970-01-01
      • 2014-05-28
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      相关资源
      最近更新 更多