问题描述
我查看了调查列表scala-lang.org 并注意到一个奇怪的问题:你能说出_"的所有用法吗?".你可以吗?如果是,请在此处执行.解释性示例表示赞赏.
I've taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: "Can you name all the uses of "_"?". Can you? If yes, please do so here. Explanatory examples are appreciated.
推荐答案
我能想到的有
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
可能还有其他我忘记了!
There may be others I have forgotten!
示例说明为什么 foo(_)
和 foo _
不同:
Example showing why foo(_)
and foo _
are different:
这个例子来自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 将给出type (_ => Unit) =>?
(Existential _
不是类型).
In the first case, process _
represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A
that will give the type (_ => Unit) => ?
(Existential _
is not a type).
在第二种情况下,process(_)
是一个 lambda;当编写一个没有显式参数类型的 lambda 时,Scala 会从 foreach
期望的参数中推断类型,并且 _ =>Unit
是一种类型(而普通的 _
不是),所以它可以被替换和推断.
In the second case, process(_)
is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach
expects, and _ => Unit
is a type (whereas just plain _
isn't), so it can be substituted and inferred.
这可能是我在 Scala 中遇到的最棘手的问题.
This may well be the trickiest gotcha in Scala I have ever encountered.
请注意,此示例在 2.13 中编译.忽略它,就像分配给下划线一样.
Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.
这篇关于Scala 中下划线的所有用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!