【问题标题】:What are all the uses of an underscore in Scala?Scala中下划线的所有用途是什么?
【发布时间】:2011-12-21 12:03:33
【问题描述】:

我查看了the listscala-lang.org 进行的调查,并注意到一个奇怪的问题:“Can you name all the uses of “_”?”。你可以吗?如果是,请在此处进行。解释性示例表示赞赏。

【问题讨论】:

标签: scala


【解决方案1】:

我能想到的有

存在类型

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 _ 为何不同的示例:

这个例子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 采用多态方法并尝试通过填充类型参数使其成为单态,但意识到没有可以为A 填充的type 将给出类型(_ => Unit) => ?(存在的_ 不是类型)。

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

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

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

【讨论】:

  • 我认为有两个或三个都适合模式匹配中的下划线用法,但是 +1 用于将字母连接到标点符号! :-)
  • @Owen 我不认为 println _ 是一个部分应用的函数。这是占位符语法的另一个例子吗?含义 map(_ + 2) 扩展为类似于 map(x => x + 2) 的东西,就像 pritnln(_) 扩展为类似于 map(x => println(x)) 的东西
  • @AndrewCassidy 实际上println _println(_) 是不同的。例如,您可以看到这一点,因为它们处理存在和多态类型略有不同。稍后会想出一个例子。
  • @AndrewCassidy 好的,我已经添加了一个示例。
  • @GiovanniBotta,我猜应该是 var x: Any = _
【解决方案2】:

来自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的一部分。

【讨论】:

  • 可能你可以添加var i: Int = _或者模式匹配的特殊情况val (a, _) = (1, 2)或者丢弃val的特殊情况for (_ &lt;- 1 to 10) doIt()
  • def f: T; def f_=(t: T) 组合用于创建可变 f 成员。
  • 模式匹配已经涵盖,方法名上的_是作弊。但是,好吧,好吧。我只是希望其他人更新常见问题解答... :-)
  • 也许你错过了这个。 vertx.newHttpServer.websocketHandler(_.writeXml(html))
  • @angelokh 这是匿名函数占位符参数,排在第五位。
【解决方案3】:

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 _
}

【讨论】:

  • 这是一个很好的解释,但它甚至没有全部。它缺少被忽略的参数/变量、连接字母和标点符号、存在类型、更高种类的类型
  • 在您的List(1,2,3,4,5).foreach(print(_)) 中,只使用List(1,2,3,4,5).foreach(print) 更具可读性,您甚至根本不需要下划线,但我想这只是风格问题
  • “_”如何在具有 .map、.flatten、.toList 功能的集合中用作占位符......有时,这让我产生了误解。 :(
【解决方案4】:

有一种用法我看这里的大家好像都忘记列出来了……

而不是这样做:

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

你可以这样做:

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

【讨论】:

  • 所以 _ 这里充当所有可用函数的命名空间?
  • @Crt no,它是n =&gt; n的简写
  • 这不是前两个答案中提到的占位符语法吗?
【解决方案5】:

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

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)

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

【讨论】:

    【解决方案6】:

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

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

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

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

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

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

    【讨论】:

      【解决方案7】:

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

        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”

      【讨论】:

      • 感觉大家的例子都是迭代的元素,我觉得这更像是低级语法糖,说lambda简洁转换
      猜你喜欢
      • 1970-01-01
      • 2022-03-02
      • 2015-04-18
      • 2017-11-07
      • 2011-08-28
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多