为什么在Option [T]的HList上映射不起作用? [英] Why does mapping over an HList of Option[T] not work?
本文介绍了为什么在Option [T]的HList上映射不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这不能编译,我也不明白为什么:
This does not compile and I do not understand why:
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
这有点令人惊讶,因为它可以编译:
This is somewhat surprising, because this does compile:
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
推荐答案
问题是您使用的是Some
而不是Option
.编译器抱怨说,尽管正在使用Option
映射器,但找不到任何东西可以转换Some
的列表.要解决此问题,您可以:
The problem is your usage of Some
instead of Option
. The compiler complains that it can't find anything to convert a list of Some
s though your Option
mapper is being used. To fix this you can:
将您的简单列表结构更改为使用Option
而不是Some
:
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
使用Some
作为映射器的类型:
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
或强制将简单类型下调为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
这篇关于为什么在Option [T]的HList上映射不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文