从Array [T]以斯卡拉IndexedSeq隐式转换[T] [英] Scala implicit conversion from Array[T] to IndexedSeq[T]
问题描述
以下code可能不会编译:
The following code wouldn't compile:
implicit class indexedSeqWithBinarySearch[T](xs: IndexedSeq[T]) {
def binarySearch(a: T) = ???
}
Array(0, 1, 2).binarySearch(1)
该方法的binarySearch
未添加到Array类。但我想,有一个从数组[T]一个隐式转换链 - > WrappedArray [T] - > mutable.IndexedSeq [T] - > collection.IndexedSeq [T]
?我怎样才能让一个阵列
的 IndexedSeq
?
the method binarySearch
is not added to the Array class. But I suppose that there's a implicit conversion chain from Array[T] -> WrappedArray[T] -> mutable.IndexedSeq[T] -> collection.IndexedSeq[T]
? How can I make an Array
an IndexedSeq
?
推荐答案
阵列
不是 IndexedSeq
的子类型但你的隐含的类定义将需要该是这样。相反,你需要采取任何类型,它的可视为的 IndexedSeq [T]
。
Array
is not a subtype of IndexedSeq
but your implicit class definition would necessitate for that to be the case. Instead, you need it to take any type that is viewable as IndexedSeq[T]
.
我用 myTail
作为一个更现实的例子在这里:
I'm using myTail
as a more realistic example here:
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]
视图势必签名。
The cast xs: IndexedSeq[T]
works because of that LS <% IndexedSeq[T]
view bound in the signature.
A&LT;%B
指定 A
必须是可见的 B
,所以需要从 A
转换为 B
范围内,在调用点,而这种转换是在方法体的效果。
A <% B
specifies that A
must be viewable as B
, so there needs to be a conversion from A
to B
within scope at the call site, and this conversion be in effect in the method body.
更新:没有关于将要德precated视图边界,隐含的类的声明看起来像:
Update: without the about-to-be-deprecated view bounds, the implicit class declaration would look like:
implicit class indexedSeqWithBinarySearch[T, LS](xs: LS)(implicit ls2ixseq: LS => IndexedSeq[T]) {
...
}
这篇关于从Array [T]以斯卡拉IndexedSeq隐式转换[T]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!