Question

If the answer to my question is already out here please link it... I did look.

I'm working through some tutorials and it struck me a little odd that this code:

val my_set = Set("one","two","three")
println("First Value:" + my_set.toArray(0))

when run from the command line resulted in this error:

$ scala settoarray.scala 
/Users/rwheadon/devStuff/scala_sandbox/so_settoarray.scala:2: error: type mismatch;
found   : Int(0)
required: ClassManifest[?]
println("First Value:" + my_set.toArray(0))
                                        ^
one error found

I googled and searched SO for some direction on providing the ClassManifest[?] requirement but couldn't get anything to work inline.

Out of curiosity I tried to do the same simple toArray() into a val and pulled the array bound successfully:

Code:

val my_set = Set("one","two","three")
val my_arry = my_set.toArray
println("First Value:" + my_arry(0))

run from console:

$ scala so_settoarray.scala 
First Value:one

What I am wondering is if there's something I need to add when attempting to just do a quick inline conversion like my_set toArray(0) for a quick println of the first element? If I must set the result of a variable I can easily accept that but my guess is that I'm missing some small point here to make inline array casts work.

(... Scala is magic right?)

Was it helpful?

Solution

The toArray method takes an implicit argument of type ClassManifest[A], where A is the element type. If you call it like mySet.toArray(0), the compiler thinks you want to pass the implicit argument explicitly and then complains that it doesn't have the right type. To avoid that, you can write it like so:

mySet.toArray.apply(0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top