6

这不编译,我不明白为什么:

import shapeless._
import poly._

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

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

这有点令人惊讶,因为它确实编译:

import shapeless._
import poly._

object choose extends (Set ~> Option) {
    def apply[T](s: Set[T]) = s.headOption
}

val sets = Set(1) :: Set("foo") :: HNil
val opts: Option[Int] :: Option[String] :: HNil = sets map choose
4

1 回答 1

6

问题是您使用 ofSome而不是Option. 编译器抱怨它找不到任何东西来转换Somes 列表,尽管您Option正在使用您的映射器。要解决此问题,您可以:

将您的简单列表构造更改为使用Option,而不是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

用作Some映射器的类型:

  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

或者强制简单的类型被向下转换为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
于 2014-09-30T18:40:27.887 回答