【问题标题】:Implicit conversion to Seq[T] from Array[T]从 Array[T] 隐式转换为 Seq[T]
【发布时间】: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


【解决方案1】:

你在某处有 import 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2011-01-01
    • 2011-04-04
    相关资源
    最近更新 更多