How to perform an operation in scala's foreach?

前端 未结 4 1813
时光取名叫无心
时光取名叫无心 2021-01-21 03:33

I am trying to understand how to perform an operation when using foreach. For e.g. how can I print element+1 of alist using foreach

4条回答
  •  攒了一身酷
    2021-01-21 03:52

    Using the Placeholder Syntax for Anonymous Functions in Scala is a bit tricky. The language specification says:

    An expression e of syntactic category Expr binds an underscore section u, if the following two conditions hold: (1) e properly contains u, and (2) there is no other expression of syntactic category Expr which is properly contained in e and which itself properly contains u.

    The bold text establishes how the Scala compiler determines which expression is the anonymous functions created with the placeholder operator - it is always the innermost expression, which properly contains the _ operator. In the case of alist.foreach(println(_+1)), the expression that binds the underscore is _ + 1. It is not bound by the entire println(_ + 1) expression since _ + 1 is properly contained in println(_ + 1). As already written in the other answers, in that case you must use the explicit syntax for anonymous functions:

    alist.foreach(x => println(x + 1))
    

    For the sake of completeness: alist.foreach(println(_+1)) translates to alist.foreach(println(x => x + 1)). Since println takes arguments of various kinds, the compiler is not able to infer uniquely a type for x and hence the missing parameter type error in that case. Even if you were to give x a type, another error will ensue since foreach expects a function that takes one argument of the elemental type of alist.

提交回复
热议问题