Reputation: 97
I tried to make my own map method in Scala and this is the result:
def map[A, B](f: A => B)(as: List[A]): List[B] =
for (i <- as) yield f(i)
And if I try to convert a List[Int] to a List[String]:
val list = List(1, 2, 3, 4, 5) //> list : List[Int] = List(1, 2, 3, 4, 5)
map(toString()) (list) //> res0: List[Char] = List(e, b, u, n, g)
I get the same result if I try:
list.map(toString()) //> res1: List[Char] = List(e, b, u, n, g)
My Question: Why gives toString() not a List("1","2"...)?
Upvotes: 1
Views: 977
Reputation: 370357
You're calling toString()
on the current object (which apparently returns something like "?ebung...") and passing the resulting string as an argument to map
.
So you might expect that to produce a type error because map
expects a function, but you're passing a string. However strings count as functions too (because RichString
implements the Function1[Int, Char]
trait) that take an integer and return the character at that index. So that's why you get a list containing those characters.
To do what you meant to do (create a function that calls toString
on its argument), you can either use x => x.toString
or _.toString
for short.
Upvotes: 4