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

在Scala中下划线的所有用途是什么?,scala,Scala,我看了一些调查,发现了一个奇怪的问题:。你能?如果是,请在此处填写。欢迎提供解释性示例。下面是对下划线用法的精彩解释 示例: 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,_,_) =>

我看了一些调查,发现了一个奇怪的问题:。你能?如果是,请在此处填写。欢迎提供解释性示例。

下面是对下划线用法的精彩解释

示例:

 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中,u在导入包时的行为类似于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)
如果尝试将函数分配给新变量,将调用该函数,并将结果分配给该变量。这种混淆是由于方法调用的可选大括号造成的。我们应该在函数名后使用u将其分配给另一个变量

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

我能想到的是

存在类型 高类类型参数 忽略的变量 忽略的参数 忽略自类型的名称 通配符模式 插值中的通配符模式 模式中的序列通配符 通配符导入 隐藏进口 给运营商的联名信 赋值运算符 占位符语法 方法值 将按名称调用参数转换为函数 默认初始值设定项 可能还有其他的我已经忘记了

显示foo_uu和foo_u不同原因的示例:

这个例子:

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

在第二种情况下,过程是lambda;在编写没有显式参数类型的lambda时,Scala会根据foreach期望的参数推断类型,=>Unit是一个类型,而plain不是,因此可以替换和推断它

这可能是我在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())

以下是使用uu的更多示例:


在上述所有示例中,一个下划线表示reduce列表中的一个元素,第一个下划线表示累加器,可以使用一个特定示例:

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

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

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

在某些场景中应用“u”将自动转换为“x$n=>x$n”

这是一个很好的解释,但它甚至没有包含所有这些。它缺少被忽略的参数/变量、连接字母和标点符号、存在类型、列表中的更高级类型1,2,3,4,5.foreachprint uu只需执行列表1,2,3,4,5.foreachprint就更具可读性,您甚至根本不需要下划线,但我想这只是风格的问题,在集合中使用function.map、.flatte、.toList……作为占位符如何。。。。。。有时,这会让我产生误解我认为在模式匹配中,有两三个都符合下划线用法,但是+1表示将字母连接到标点符号!:-@欧文,我不认为println是一个部分应用的函数。这是占位符语法的另一个例子,对吗?意思是map_u2扩展到类似于mapx=>x+2的东西,就像pritnln_uu2扩展到类似于mapx=>printlnx@AndrewCassidy实际上println和println是不同的。例如,您可以看到,它们处理存在类型和多态类型的方式略有不同。过一会儿我会想出一个例子。@AndrewCassidy好的,我已经添加了一个例子。@GiovanniBotta,我想它应该是var x:Any=\u可能是您可以添加var I:Int=\u或模式匹配val a的特例,\u=1,2或为u和def:T丢弃val的特例;def f_uuT=t:t用于创建可变f成员的组合。模式匹配已包含在内,并且uon方法名称存在欺骗。但是,好吧,好吧。我只希望其他人更新FAQ…:-也许你错过了这个。vertx.newHttpServer.websocketHandler。writeXmlhtml@angelokh这是匿名函数占位符参数,排在列表的第五位。不久前我读了这组像样的幻灯片:参见SlideShare觉得每个人的示例都是迭代的一个元素,我认为这更像是一种低级语法糖,said lambda简明转换在这里充当所有可用函数的名称空间?@Crt否,它充当n=>nisn的简写,这不是前两个答案中提到的占位符语法吗?
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
trait PlaceholderExample {
  def process[A](f: A => Unit)

  val set: Set[_ => Unit]

  set.foreach(process _) // Error 
  set.foreach(process(_)) // No Error
}
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)
  type StringMatcher = String => (String => Boolean)

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