I’m just starting to learn scala and I came across the following case in the REPL:
(1 to 3).map(toString)
\\=> IndexedSeq[Char] = Vector(l, i, n)
What I was expecting can be achieved by:
(1 to 3).map(n => n.toString)
\\=> IndexedSeq[String] = Vector(1, 2, 3)
Strangely, this works as expected
(1 to 3)(0)
\\=> Int = 1
Just wondering what the reasoning is here?
1 Like
Nice puzzler!
What’s happening here is that you’re calling the toString
method of the object that is wrapping your code. You can see that by evaluating println(toString)
. That String
is then implicitly converted to a WrappedString
because that is a subtype of Int => Char
which conforms to the expected type of the argument to the map
function. The same happens in this code: "bar"(1)
will return 'a'
because it’s the character at index 1.
What you probably meant to write is
(1 to 3).map(_.toString)
3 Likes
Hi Jasper,
thanks for the quick explanation. I can follow what you wrote in the REPL:
scala> println(toString)
\\=> $line4.$read$$iw@7d3c09ec
and the index values 1 to 3
map to the characters l, i, n
, which is more obvious when you increase the length of the range:
(1 to 10).map(toString)
\\=> IndexedSeq[Char] = Vector(l, i, n, e, 3, 4, ., $, r, e)
You’re right, I should have used the underscore!