5

I try to slice an 1D Array[Double] using the slice method. I've written a method which returns the start and end index as a tuple (Int,Int).

  def getSliceRange(): (Int,Int) = {
    val start =   ...
    val end =  ...
    return (start,end)
  }

How can I use the return value of getSliceRange directly?

I tried:

myArray.slice.tupled(getSliceRange())

But this gives my a compile-Error:

Error:(162, 13) missing arguments for method slice in trait IndexedSeqOptimized;
follow this method with `_' if you want to treat it as a partially applied function
  myArray.slice.tupled(getSliceRange())

2 Answers 2

5

I think the problem is the implicit conversion from Array to ArrayOps (which gets slice from GenTraversableLike).

val doubleArray = Array(1d, 2, 3, 4)

(doubleArray.slice(_, _)).tupled

Function.tupled[Int, Int, Array[Double]](doubleArray.slice)

(doubleArray.slice: (Int, Int) => Array[Double]).tupled
Sign up to request clarification or add additional context in comments.

3 Comments

in short: (myArray.slice(_, _)).tupled(getSliceRange()) does the trick.
Can you explain what (doubleArray.slice(_, _)).tupled means?
doubleArray.slice(_, _) is the same as (a, b) => doubleArray.slice(a, b), we need the parentheses because we want to call tupled on the function and not on the result of slice .
1

Two options here, the first one is to call your function twice:

myArray.slice(getSliceRange()._1, getSliceRange()._2)

or to save your Tuple beforehand:

val myTuple: (Int, Int) = getSliceRange()
myArray.slice(myTuple._1, myTuple._2)

Edit: I leave this here just in case but Peter Neyens posted the expected answer.

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.