How to perform an operation in scala's foreach?

前端 未结 4 1840
时光取名叫无心
时光取名叫无心 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:51

    My Scala is exceedingly rusty, and I don't have a medium to test the code on, so please notify me of any syntax issues.

    Scala has issues automatically inferring the type of parameters of anonymous functions in some circumstances. From my experience, it's best to just say the types explicitly, else risk recieving the wrath of the compiler. If all you're trying to do is add one to each element and print the result, try:

    alist.foreach(
        n: Int => println(n + 1)
    )
    

    Note the purpose of foreach though. It is intended to be used when you want to carry out side effects over a list. If your intent was to create a second list where each element is + 1 the original list, use a generator/map function instead.

    And regarding your second example, if you think on it, it will be clear why it doesn't work. println returns void/Unit, which you then try to access the toInt method of.

    Edit:

    As noted in the comments, in this case, type annotations aren't required. I still prefer to place them though. I prefer explicit types unless they're bloating the code (personal choice).

提交回复
热议问题