What are all the uses of an underscore in Scala?

后端 未结 7 1175
南笙
南笙 2020-11-21 07:24

I\'ve taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: \"Can you name all the uses of “_”?\". Can you? If yes, please do so here.

7条回答
  •  無奈伤痛
    2020-11-21 07:44

    Here are some more examples where _ is used:

    val nums = List(1,2,3,4,5,6,7,8,9,10)
    
    nums filter (_ % 2 == 0)
    
    nums reduce (_ + _)
    
    nums.exists(_ > 5)
    
    nums.takeWhile(_ < 8)
    

    In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)

提交回复
热议问题