从Array[T]到Seq[T]的隐式转换

3
我在使用视图界限时遇到了一些问题。我编写了以下函数,该函数应接受任何可视为Seq[T]的对象seq并在其为空时返回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控制台中对我有效。 - Ashalynd
一样,你用的是哪个版本的Scala? - Gabriele Petronella
1
当它只是scala.collection.Seq时,它有效,但对于原始帖子中的scala.collection.immutable.Seq无效。我不认为从Array[T]scala.collection.immutable.Seq[T]有视图... - Patryk Ćwiek
1个回答

3

你是否在某个地方导入了scala.collection.immutable.Seq

scala.Predef中定义了一系列名为*ArrayOps的隐式视图,用于将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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接