【发布时间】:2011-12-21 12:03:33
【问题描述】:
我查看了the list 对scala-lang.org 进行的调查,并注意到一个奇怪的问题:“Can you name all the uses of “_”?”。你可以吗?如果是,请在此处进行。解释性示例表示赞赏。
【问题讨论】:
-
不久前我读到了这组不错的幻灯片:Scala Dreaded Underscore
标签: scala
我查看了the list 对scala-lang.org 进行的调查,并注意到一个奇怪的问题:“Can you name all the uses of “_”?”。你可以吗?如果是,请在此处进行。解释性示例表示赞赏。
【问题讨论】:
标签: scala
我能想到的有
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 中编译。忽略它,就像它被分配给下划线一样。
【讨论】:
println _ 和println(_) 是不同的。例如,您可以看到这一点,因为它们处理存在和多态类型略有不同。稍后会想出一个例子。
来自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 (_ <- 1 to 10) doIt()
def f: T; def f_=(t: T) 组合用于创建可变 f 成员。
_是作弊。但是,好吧,好吧。我只是希望其他人更新常见问题解答... :-)
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) 更具可读性,您甚至根本不需要下划线,但我想这只是风格问题
有一种用法我看这里的大家好像都忘记列出来了……
而不是这样做:
List("foo", "bar", "baz").map(n => n.toUpperCase())
你可以这样做:
List("foo", "bar", "baz").map(_.toUpperCase())
【讨论】:
n => n的简写
以下是使用_ 的更多示例:
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)
在以上所有示例中,一个下划线代表列表中的一个元素(用于减少第一个下划线代表累加器)
【讨论】:
除了JAiro提到的usages之外,我喜欢这个:
def getConnectionProps = {
( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}
如果有人需要所有连接属性,他可以这样做:
val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps
如果你只需要一个主机和一个端口,你可以这样做:
val ( host, port, _, _ ) = getConnectionProps
【讨论】:
有一个使用“_”的具体例子:
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”
【讨论】: