1

I want to access via one-liner a list-to-array element by index.

This gives me an error:

Array(1,2,3)(2)  // 3
List(1,2,3).toArray(2) // error 
(List(1,2,3).toArray)(2) // error

// error: type mismatch;
// found   : scala.this.Int(2)
// required: reflect.this.ClassTag[?]

However, this works:

val a = Array(1,2,3)
val b = List(1,2,3).toArray


println(a(2))  // 3
println(b(2))  // 3

Why is that so and how to make a solution without making extra val's?

Scalafiddle

1
  • 1
    Why not simply b(2)? If you are only going to access it one time, it would be more efficient this way. Other alternative (if you still want to make the conversion) is b.toArray.apply(2). Commented Sep 20, 2019 at 20:01

1 Answer 1

1

The type checker is making the wrong choice. Try giving it a hint.

println((List(1,2,3).toArray: Array[Int])(2)) 
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.