Scala 作为一门函数式编程语言,对习惯了指令式编程语言的同学来说,会不大习惯,这里除了思维方式之外,还有语法层面的,比如 underscore(下划线)就会出现在多种场合,令初学者相当疑惑,今天就来总结下 Scala 中下划线的用法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
|
这里需要注意的是,以下两种写法实现的是完全不一样的功能:
1 2 3 |
|
Example showing why foo(_) and foo _ are different:
1 2 3 4 5 6 7 8 |
|
In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).
In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn‘t), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
Refer:
[1] What are all the uses of an underscore in Scala?
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala
[2] Scala punctuation (AKA symbols and operators)
[3] Scala中的下划线到底有多少种应用场景?
http://www.zhihu.com/question/21622725
[4] Strange type mismatch when using member access instead of extractor
[5] Scala简明教程
http://colobu.com/2015/01/14/Scala-Quick-Start-for-Java-Programmers/