-1

I've learnt Scala for 1,5 months at the university - what I had is: collections, pattern matching, functions on collections but my question is: what does really that underscore mean? I saw you guys using it almost everywhere and I don't know how to read it to be honest. For example:

val list1 = List(1,2,3,4,5)
list1.map(_ * 2) or list1.map(n => n*2) 

what's the difference there? What could be hidden under that underscore symbol? I saw you guys also using almost always in reduceLeft(_ + _) something like this - how could I replace that to see, what is hidden under that?

I also have question if you recommend that page: www.scala-exercises.org to practice and learn Scala? I can't create any exercises myself and would like to practice more exercise than I get on lessons.

squall
  • 139
  • 5
  • 1
    Does [this](https://www.geeksforgeeks.org/placeholder-syntax-in-scala/#:~:text=Scala%20allows%20the%20use%20of,for%20one%20or%20more%20parameters.&text=Multiple%20underscores%20means%20multiple%20parameters,or%20more%20parameters%20only%20once.) help? – AminMal Apr 08 '21 at 08:38
  • 1
    https://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala – Naetmul Apr 08 '21 at 08:43

1 Answers1

1

Underscores used to replace the N'th argument with an anonymous argument in a function, for example, the following lines are equivalent

list1.map(_ * 2)
list1.map(n => n * 2) 

Regarding the reduceLeft(_ + _), so as said before, its replacing the 1'th argument and 2'th argument as follows, thus they are equivalent

list1.reduceLeft(_ + _)
list1.reduceLeft((a,b) => a + b)

And so on...

Hope its clear now

Zvi Mints
  • 1,072
  • 1
  • 8
  • 20
  • thank you, but about the reduce it's quite difficult for me: so under first underscore I have (a,b) => a, and under second one I have only b? – squall Apr 08 '21 at 08:57
  • 2
    Please, do not answer duplicate questions. If you are *really* confident that there is something important missing that is not yet covered in one of the 13 answers that already exist on the duplicate target, then write an answer *over there*. Answering duplicate questions spreads the information out across multiple places which is the *exact opposite* of what [so] tries to do, namely provide the highest-quality possible information in a single place. – Jörg W Mittag Apr 08 '21 at 09:14