我在视图边界方面遇到了一些问题。我编写了以下函数,它应该将任何seq
可查看的对象作为 aSeq[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]
to的隐式转换WrappedArray[T]
吗?不应该scala.Predef.wrapRefArray
管这个吗?