【问题标题】:Scala implicit conversion from Array[T] to IndexedSeq[T]从 Array[T] 到 IndexedSeq[T] 的 Scala 隐式转换
【发布时间】:2014-11-04 02:19:31
【问题描述】:

以下代码无法编译:

  implicit class indexedSeqWithBinarySearch[T](xs: IndexedSeq[T]) {
    def binarySearch(a: T) = ???
  }

  Array(0, 1, 2).binarySearch(1)

方法binarySearch 没有添加到Array 类中。但我想有一个来自 Array[T] -> WrappedArray[T] -> mutable.IndexedSeq[T] -> collection.IndexedSeq[T] 的隐式转换链?如何将Array 设为IndexedSeq

【问题讨论】:

  • 一种选择是从您正在使用的特定集合类型定义转换;这样你也不依赖继承(即子类型多态性)。
  • 是的,但是为什么不能将Arrays 转换为IndexedSeqs?
  • 可以,但调用签名中的x: X 意味着x 必须是X 的实际子类型的实例,而不仅仅是可转换为X;请参阅我的答案以获得解决方案。

标签: arrays scala implicit-conversion


【解决方案1】:

Array 不是IndexedSeq 的子类型,但您的隐式类定义需要这种情况。相反,您需要它采用任何 可见 IndexedSeq[T] 的类型。

我在这里使用myTail 作为更现实的例子:

implicit class indexedSeqWithBinarySearch[T, LS <% IndexedSeq[T]](xs: LS) {
  def myTail = {
    val xs1 = xs: IndexedSeq[T] // now the cast works
    xs1.tail
  }
}

println(Array(1, 2, 3).myTail)

演员xs: IndexedSeq[T] 之所以有效,是因为签名中绑定了LS &lt;% IndexedSeq[T] 视图。

A &lt;% B 指定A 必须以B 可见,因此需要在调用站点的范围内从A 转换为B,并且该转换在方法中生效身体。


更新:没有即将被弃用的视图边界,隐式类声明将如下所示:

implicit class indexedSeqWithBinarySearch[T, LS](xs: LS)(implicit ls2ixseq: LS => IndexedSeq[T]) {
  ...
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2011-01-01
  • 1970-01-01
相关资源
最近更新 更多