【发布时间】:2014-10-02 17:29:43
【问题描述】:
所以我有以下方法将Seq-like 对象包装在Option 中。
def noneIfEmpty[S <% Seq[_]](seq: S): Option[S] = {
if (seq.isEmpty) None else Some(seq)
}
我希望能够使用这种方法来转换包装在Try 中的计算结果。假设我用List[Int] 来做这个:
scala> val tryList = Try(List(1,2,3))
tryList: scala.util.Try[List[Int]] = Success(List(1, 2, 3))
我应该能够使用noneIfEmpty 将Try[List[Int]] 映射到Try[Option[List[Int]]]。如果我使用匿名函数并将列表显式传递给 noneIfEmpty...
scala> tryList map (list => noneIfEmpty(list))
res1: scala.util.Try[Option[List[Int]]] = Success(Some(List(1, 2, 3)))
...但是如果我尝试将 noneIfEmpty 作为部分应用的函数传递,它会中断。
scala> tryList map noneIfEmpty _
<console>:40: error: No implicit view available from S => Seq[_].
tryList map noneIfEmpty _
^
如果我将noneIfEmpty 缩小为只接受列表,它也可以正常工作:
scala> def noneIfEmptyList[A](list: List[A]): Option[List[A]] = noneIfEmpty(list)
noneIfEmptyList: [A](list: List[A])Option[List[A]]
scala> tryList map noneIfEmptyList _
res2: scala.util.Try[Option[List[Int]]] = Success(Some(List(1, 2, 3)))
这里发生了什么?工作中是否有某种类型的擦除巫术?
【问题讨论】:
标签: scala implicit-conversion implicit