1
scala> val arr = Array[Any](Array(1.0, 2.0))
arr: Array[Any] = Array(Array(1.0, 2.0))

scala> arr(0)
res28: Any = Array(1.0, 2.0)

The array arr is fixed. How to change arr(0) to Array[Double] in this situation?

2
  • don't force the return type to be any. Commented Aug 29, 2018 at 7:56
  • Inference as Any generally means something is wrong Commented Aug 29, 2018 at 14:29

1 Answer 1

3

There are three options:

1) Don't cast to Array[Any] in the first place:

val arr: Array[Array[Double]] = Array(Array(1.0, 2.0))
val arr0: Array[Double] = arr(0)      

2) Use match:

val arr0: Array[Double] = arr(0) match {
  case a: Array[Double] => a
}

3) Use asInstanceOf:

val arr0: Array[Double] = arr(0).asInstanceOf[Array[Double]]

These are in order of preference, with the option 1 being by far the best solution because it avoids throwing away type information.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd prefer 3 to 2 (with the caveat that they are both bad); 2 is just pointlessly longer and less efficient.

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.