以下代码无法编译:
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
?
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 <% IndexedSeq[T]
签名中绑定了该视图。
A <% B
指定A
必须以形式可见B
,因此在调用站点的作用域内必须存在从A
到的转换B
,并且此转换在方法主体中有效。
更新:没有即将弃用的视图范围,隐式类声明将类似于:
implicit class indexedSeqWithBinarySearch[T, LS](xs: LS)(implicit ls2ixseq: LS => IndexedSeq[T]) {
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句