Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: map(f) and map(_.f)

Tags:

scala

I thought in scala map(f) is the same as map(_.f) as map(x => x.f), but turns out it is not

scala> val a = List(1,2,3)
val a: List[Int] = List(1, 2, 3)

scala> a.map(toString)
val res7: List[Char] = List(l, i, n)

scala> a.map(_.toString)
val res8: List[String] = List(1, 2, 3)

What happenes when a.map(toString) is called? Where did the three charaacters l, i, and n come from?

like image 246
gefei Avatar asked Nov 20 '25 07:11

gefei


1 Answers

map(f) is not the same as map(_.f()). It's the same as map(f(_)). That is, it's going to call f(x), not x.f(), for each x in the list.

So a.map(toString) should be an error because the normal toString method does not take any arguments. My guess is that in your REPL session you've defined your own toString method that takes an argument and that's the one that's being called.

like image 132
sepp2k Avatar answered Nov 21 '25 22:11

sepp2k