gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:41:05 27 4
gpt4 key购买 nike

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

最佳答案

你有没有在某处导入scala.collection.immutable.Seq

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

关于scala - 从 Array[T] 到 Seq[T] 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26131343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com