Why does mapping over an HList of Option[T] not work?

依然范特西╮ 提交于 2019-12-05 08:31:04

The problem is your usage of Some instead of Option. The compiler complains that it can't find anything to convert a list of Somes though your Option mapper is being used. To fix this you can:

Change your simple list construction to use Option instead of Some:

  object option extends (Option ~> List) {
    def apply[T](t: Option[T]) = t.toList
  }

  val simple = Option(1) :: Option("hello") :: Option(true) :: HNil
  val opts2: List[Int] :: List[String] :: List[Boolean] :: HNil = simple map option

Use Some as the type of your mapper:

  object option extends (Some ~> List) {
    def apply[T](t: Some[T]) = t.toList
  }

  val simple = Some(1) :: Some("hello") :: Some(true) :: HNil
  val opts2: List[Int] :: List[String] :: List[Boolean] :: HNil = simple map option

Or force the type of simple to be downcast to Option:

  object option extends (Option ~> List) {
    def apply[T](t: Option[T]) = t.toList
  }

  val simple: Option[Int] :: Option[String] :: Option[Boolean] :: HNil = Some(1) :: Some("hello") :: Some(true) :: HNil
  val opts2: List[Int] :: List[String] :: List[Boolean] :: HNil = simple map option
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!