3

我在视图边界方面遇到了一些问题。我编写了以下函数,它应该将任何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管这个吗?

4

1 回答 1

3

你有进口的scala.collection.immutable.Seq地方吗?

有系列隐式视图命名*ArrayOps定义在scala.Predef其中转换Array[T]scala.collection.mutable.ArrayOps[T],但不是immutable.Seq

scala> def noneIfEmpty[S <% collection.Seq[_]](seq: S): Option[S] =
     |   if(seq.isEmpty) None else Some(seq)
noneIfEmpty: [S](seq: S)(implicit evidence$1: S => Seq[_])Option[S]

scala> noneIfEmpty(Array[Int]())
res0: Option[Array[Int]] = None

scala> noneIfEmpty(Array[Int](1, 2, 3))
res1: Option[Array[Int]] = Some([I@7c92fffb)
于 2014-10-01T05:34:55.440 回答