[英]What are all the uses of an underscore in Scala?
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 “_”? ".我查看了scala-lang.org上的调查列表,注意到一个奇怪的问题:“你能说出“_”的所有用法吗? ”。 Can you?你是否可以? If yes, please do so here.如果是,请在此处执行。 Explanatory examples are appreciated.解释性示例表示赞赏。
The ones I can think of are我能想到的有
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!可能还有其他我忘记了!
Example showing why foo(_)
and foo _
are different:显示为什么foo(_)
和foo _
不同的示例:
This example comes from 0__ :这个例子来自 0__ :
trait PlaceholderExample {
def process[A](f: A => Unit)
val set: Set[_ => Unit]
set.foreach(process _) // Error
set.foreach(process(_)) // No Error
}
In the first case, process _
represents a method;第一种情况, process _
代表一个方法; 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) => ?
阶取多晶型的方法和尝试以通过在类型参数填充以使其单形,但认识到没有任何类型,可在填充于A
,这将使类型(_ => Unit) => ?
(Existential _
is not a type). (存在_
不是一种类型)。
In the second case, process(_)
is a lambda;在第二种情况下, process(_)
是一个 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.当编写一个没有显式参数类型的 lambda 时,Scala 从foreach
期望的参数推断类型,并且_ => Unit
是一种类型(而只是普通的_
不是),所以它可以被替换和推断。
This may well be the trickiest gotcha in Scala I have ever encountered.这很可能是我在 Scala 中遇到的最棘手的问题。
Note that this example compiles in 2.13.请注意,此示例在 2.13 中编译。 Ignore it like it was assigned to underscore.忽略它,就像它被分配给下划线一样。
From (my entry) in the FAQ , which I certainly do not guarantee to be complete (I added two entries just two days ago):来自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 is also part of this question .这也是这个问题的一部分。
An excellent explanation of the uses of the underscore is Scala _ [underscore] magic .下划线用法的一个很好的解释是Scala _ [underscore] magic 。
Examples:例子:
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))
In Scala, _
acts similar to *
in Java while importing packages.在 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 => _ , _ }
In Scala, a getter and setter will be implicitly defined for all non-private vars in a object.在 Scala 中,将为对象中的所有非私有变量隐式定义 getter 和 setter。 The getter name is same as the variable name and _=
is added for the setter name. getter 名称与变量名称相同,并且为 setter 名称添加了_=
。
class Test {
private var a = 0
def age = a
def age_=(n:Int) = {
require(n>0)
a = n
}
}
Usage:用法:
val t = new Test
t.age = 5
println(t.age)
If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable.如果您尝试将函数分配给新变量,则会调用该函数并将结果分配给该变量。 This confusion occurs due to the optional braces for method invocation.这种混淆是由于方法调用的可选大括号造成的。 We should use _ after the function name to assign it to another variable.我们应该在函数名后使用 _ 将其分配给另一个变量。
class Test {
def fun = {
// Some code
}
val funLike = fun _
}
There is one usage I can see everyone here seems to have forgotten to list...有一种用法我看到这里的每个人似乎都忘记列出......
Rather than doing this:而不是这样做:
List("foo", "bar", "baz").map(n => n.toUpperCase())
You could can simply do this:你可以简单地这样做:
List("foo", "bar", "baz").map(_.toUpperCase())
Here are some more examples where _
is used:以下是使用_
更多示例:
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)
In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)在上述所有示例中,一个下划线表示列表中的一个元素(为了减少第一个下划线表示累加器)
Besides theusages that JAiro mentioned, I like this one:除了 JAiro 提到的用法,我喜欢这个:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
If someone needs all connection properties, he can do:如果有人需要所有连接属性,他可以这样做:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
If you need just a host and a port, you can do:如果你只需要一个主机和一个端口,你可以这样做:
val ( host, port, _, _ ) = getConnectionProps
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]
There is a specific example that "_" be used:有一个使用“_”的具体示例:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :可能等于:
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”在某些情况下应用“_”会自动转换为“(x$n) => x$n ”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.