【发布时间】:2014-09-30 22:40:35
【问题描述】:
我在视图边界方面遇到了一些问题。我编写了以下函数,它应该将任何可查看的对象seq 视为Seq[T],如果它为空则返回None,否则返回Some(seq)。
def noneIfEmpty[T, S <% Seq[T]](seq: S): Option[S] =
if (seq.isEmpty) None else Some(seq)
让我们定义函数...
scala> def noneIfEmpty[T, S <% Seq[T]](seq: S): Option[S] = ...
noneIfEmpty: [T, S](seq: S)(implicit evidence$1: S => scala.collection.immutable.Seq[T])Option[S]
好的,函数签名看起来正确。让我们尝试一个空列表...
scala> noneIfEmpty(List())
res54: Option[List[Nothing]] = None
到目前为止一切顺利。现在让我们尝试一个非空列表...
scala> noneIfEmpty(List(1,2,3))
res55: Option[List[Int]] = Some(List(1, 2, 3))
太好了。数组呢?
scala> noneIfEmpty(Array())
<console>:15: error: No implicit view available from Array[Nothing] => scala.collection.immutable.Seq[Any].
noneIfEmpty(Array())
^
不太好。这里发生了什么?不是有从Array[T] 到WrappedArray[T] 的隐式转换吗? scala.Predef.wrapRefArray 不应该处理这个吗?
【问题讨论】:
-
在 2.11.2 控制台中为我工作。
-
这里一样,你用的是什么版本的scala?
-
它只适用于
scala.collection.Seq,但不适用于scala.collection.immutable.Seq,如原始帖子中所示。我不认为有从Array[T]到scala.collection.immutable.Seq[T]的视图...
标签: scala types implicit-conversion implicit view-bound