我尝试过这个:
implicit class ArrayExtensions[A](a: Array[A]) {
/**
* Sort a slice [from, until) of this array
*/
def sort(from: Int, until: Int)(implicit cmp: Ordering[A]) = java.util.Arrays.sort(a, from, until, cmp)
}
但是,我想我正在点击 a bug in the compiler :
[error] found : Array[A]
[error] required: Array[? with Object]
[error] Note: A >: ? with Object, but class Array is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ >: ? with Object`. (SLS 3.2.10)
[error] def sort(from: Int, until: Int)(implicit cmp: Ordering[A]) = java.util.Arrays.sort(a, from, until, cmp)
我该如何解决这个问题?
最佳答案
您的问题的答案就在您引用的错误中:“Java 泛型数组不能与 Scala 值类型一起使用”。正如错误所说,真正的问题是错误消息没有太大帮助。问题是你对 A 的类型没有任何限制,但并不是所有的 Scala 类型都可以用作 Java 泛型类型参数,只有引用类型可以。试试这个:
implicit class ArrayExtensions[A <: AnyRef](a: Array[A]) {
/**
* Sort a slice [from, until) of this array
*/
def sort(from: Int, until: Int)(implicit cmp: Ordering[A]) = java.util.Arrays.sort(a, from, until, cmp)
}
AnyRef
对应于 Java Object
,而 Any
包括非 Java 对象的 Scala 类型(例如 Int
)。
关于scala - 在 Scala 中对数组进行就地排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35788492/