0

I am trying to wrap java.util.Array.binarySearch in a generic fashion in Scala, but the following code doesn't work:

 def binarySlice[T](minValue: T, array: Array[T]): Array[T] = {
   val i = java.util.Arrays.binarySearch(array, minValue)
   val idx = if (i > 0) i else -i - 1
   array.slice(idx, array.length)
 }

The error is: Cannot resolve overloaded method 'binarySearch'. What should I do to make this code work?

3
  • Which binarySearch method are you trying to use? There are two implementations with Array[T] but they need another parameters. Commented Sep 26, 2018 at 17:54
  • The one with only 2 arguments, the second one being the target value? Commented Sep 26, 2018 at 19:22
  • There are two binarySearch methods with Array[T] argument, none of them have 2 arguments. public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c) and public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c) Commented Sep 26, 2018 at 19:26

1 Answer 1

1

See: Scala replacement for Arrays.binarySearch:

def binarySlice[T <: AnyRef](minValue: T, array: Array[T]): Array[T] = {
   val i = java.util.Arrays.binarySearch(array.asInstanceOf[Array[AnyRef]], minValue)
   val idx = if (i > 0) i else -i - 1
   array.slice(idx, array.length)
 }

You can not use it for primitives. It is work-around for int:

scala> binarySlice[java.lang.Integer](3, Array(0,3,7,8))
res6: Array[Integer] = Array(3, 7, 8)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.