我看了一下scala-lang.org上的调查列表,注意到一个奇怪的问题:“你能说出“_”的所有用法吗?”你能吗?如果有,请在这里填写。解释性的例子是赞赏的。


当前回答

有一种用法我发现在座的每个人似乎都忘了列出…

而不是这样做:

List("foo", "bar", "baz").map(n => n.toUpperCase())

你可以简单地这样做:

List("foo", "bar", "baz").map(_.toUpperCase())

其他回答

除了JAiro提到的用法,我还喜欢这个用法:

def getConnectionProps = {
    ( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}

如果有人需要所有的连接属性,他可以这样做:

val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps

如果你只需要一个主机和一个端口,你可以做:

val ( host, port, _, _ ) = getConnectionProps

这里有一个使用“_”的具体例子:

  type StringMatcher = String => (String => Boolean)

  def starts: StringMatcher = (prefix:String) => _ startsWith prefix

可能等于:

  def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix

在某些情况下应用" _ "将自动转换为" (x$n) => x$n "

有一种用法我发现在座的每个人似乎都忘了列出…

而不是这样做:

List("foo", "bar", "baz").map(n => n.toUpperCase())

你可以简单地这样做:

List("foo", "bar", "baz").map(_.toUpperCase())

下面是一些使用_的例子:

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)

在上面的例子中,一个下划线代表列表中的一个元素(对于reduce,第一个下划线代表累加器)

从FAQ中的(我的条目),我当然不保证是完整的(我两天前添加了两个条目):

import scala._    // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]]       // Higher kinded type parameter
def f(m: M[_])    // Existential type
_ + _             // Anonymous function placeholder parameter
m _               // Eta expansion of method into method value
m(_)              // Partial function application
_ => 5            // Discarded parameter
case _ =>         // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10)  // same thing
f(xs: _*)         // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _    // Initialization to the default value
def abc_<>!       // An underscore must separate alphanumerics from symbols on identifiers
t._2              // Part of a method name, such as tuple getters
1_000_000         // Numeric literal separator (Scala 2.13+)

这也是这个问题的一部分。