Underscore in List.filter

前端 未结 3 2031
夕颜
夕颜 2020-12-02 00:15

Why this is not working:

List(true,false).filter(_).size

The error says:

:8: error: missing parameter type f         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-02 00:55

    I see the error message is much improved! Let's see what the error message said you wrote, and your working version:

    ((x$1) => List(true, false).filter(x$1).size)
              List(true,false).filter(a => a).size
    

    Or, adjusting spaces, parenthesis and variable names:

    a => List(true, false).filter(a     ).size
         List(true, false).filter(a => a).size
    

    Does it look the same now?

    Briefly, when you pass underscore in place of a parameter, you are doing partial function application. You are probably more familiar with underscores being used as placeholders for parameters in anonymous functions, which is what happens when it appears in an expression, like _ + 1. These two uses are different, even if they both result in an anonymous function.

提交回复
热议问题