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

时间:2011-11-03 19:43:46

标签: scala

我查看了the listscala-lang.org进行的调查,发现了一个奇怪的问题:“Can you name all the uses of “_”?”。你能?如果是,请在此处进行。感谢解释性的例子。

8 个答案:

答案 0 :(得分:528)

我能想到的是

存在类型

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

更高的kinded类型参数

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 _

将call-by-name参数转换为函数

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

默认初始化程序

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

可能还有其他人我已经忘记了!


示例显示foo(_)foo _不同的原因:

此示例comes from 0__

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

  val set: Set[_ => Unit]

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

在第一种情况下,process _代表一种方法; Scala采用多态方法并尝试通过填充type参数使其变为单态,但意识到没有 type 可以为A填充,它将提供类型{{ 1}}(存在(_ => Unit) => ?不是类型)。

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

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

请注意,此示例在2.13中编译。忽略它就像分配给下划线一样。

答案 1 :(得分:154)

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

这也是this question的一部分。

答案 2 :(得分:77)

对下划线使用的一个很好的解释是 Scala _ [underscore] 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 _
}

答案 3 :(得分:30)

有一种用法我可以看到这里的每个人似乎都忘了列出......

而不是这样做:

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

你可以简单地这样做:

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

答案 4 :(得分:11)

以下是一些使用_的示例:

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)

在上面的所有示例中,一个下划线表示列表中的元素(用于减少第一个下划线表示累加器)

答案 5 :(得分:10)

除了JAiro提到的usages之外,我喜欢这个:

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

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

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

如果您只需要主机和端口,则可以执行以下操作:

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

答案 6 :(得分:7)

import scala._    // Wild card -- all of Scala is imported

import scala.{ Predef => _, _ } // Exclusion, 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

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

Please check the below link for more details

[https://docs.scala-lang.org/tutorials/FAQ/finding-symbols.html][1]

答案 7 :(得分:-1)

有一个特定的例子,使用“_”:

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

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

可能等于:

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

在某些情况下应用“_”会自动转换为“(x $ n)=&gt; x $ n“

相关问题