在Scala中下划线的所有用途是什么?

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

166594 次浏览

Scala _[下划线]magic很好地解释了下划线的用法。

例子:

 def matchTest(x: Int): String = x match {
case 1 => "one"
case 2 => "two"
case _ => "anything other than one and two"
}


expr match {
case List(1,_,_) => " a list with three element and the first element is 1"
case List(_*)  => " a list with zero or more elements "
case Map[_,_] => " matches a map with any key type and any value type "
case _ =>
}


List(1,2,3,4,5).foreach(print(_))
// Doing the same without underscore:
List(1,2,3,4,5).foreach( a => print(a))

在Scala中,导入包时_与Java中的*类似。

// Imports all the classes in the package matching
import scala.util.matching._


// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._


// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }


// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }

在Scala中,getter和setter将为对象中的所有非私有变量隐式定义。getter名称与变量名称相同,并且为setter名称添加了_=

class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}

用法:

val t = new Test
t.age = 5
println(t.age)

如果您尝试将一个函数赋值给一个新变量,该函数将被调用,结果将被赋值给该变量。这种混淆是由于方法调用的可选花括号造成的。我们应该在函数名后使用_将其赋值给另一个变量。

class Test {
def fun = {
// Some code
}
val funLike = fun _
}

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

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

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

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

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

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

我能想到的是

存在的类型

def foo(l: List[Option[_]]) = ...

更高类型的类型参数

case class A[K[_],T](a: K[T])

忽略的变量

val _ = 5

忽略参数

List(1, 2, 3) foreach { _ => println("Hi") }

忽略了自我类型的名称

trait MySeq { _: Seq[_] => }

通配符模式

Some(5) match { case Some(_) => println("Yes") }

插值中的通配符模式

"abc" match { case s"a$_c" => }

模式中的序列通配符

C(1, 2, 3) match { case C(vs @ _*) => vs.foreach(f(_)) }

通配符进口

import java.util._

隐藏的进口

import java.util.{ArrayList => _, _}

致运营商的联名信

def bang_!(x: Int) = 5

赋值操作符

def foo_=(x: Int) { ... }

占位符的语法

List(1, 2, 3) map (_ + 2)

值方法

List(1, 2, 3) foreach println _

将名称调用参数转换为函数

def toFunction(callByName: => Int): () => Int = callByName _

默认初始化

var x: String = _   // unloved syntax may be eliminated

也许还有其他人我已经忘记了!


示例显示为什么foo(_)foo _是不同的:

这个例子来自0__:

trait PlaceholderExample {
def process[A](f: A => Unit)


val set: Set[_ => Unit]


set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}

在第一种情况下,process _表示一个方法;Scala采用多态方法,并试图通过填充类型参数来使其成为单态的,但意识到没有类型可以为A填充,从而给出类型(_ => Unit) => ?(存在_不是类型)。

在第二种情况下,process(_)是一个lambda;当编写一个没有显式参数类型的lambda时,Scala从foreach期望的参数中推断出类型,而_ => Unit 是类型(而普通的_不是),所以它可以被替换和推断。

这可能是我在Scala中遇到的最棘手的问题。

注意,这个示例在2.13中编译。忽略它,就像它被指定为下划线一样。

常见问题解答中的(我的条目),我当然不保证是完整的(我两天前添加了两个条目):

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+)

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

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

而不是这样做:

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,第一个下划线代表累加器)

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

  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 "