The ones I can think of are
Existential types
def foo(l: List[Option[_]]) = …
Higher kinded type parameters
case class A[K[_],T](a: K[T])
Ignored variables
val _ = 5
Ignored parameters
List(1, 2, 3) foreach { _ => println(“Hi”) }
Wildcard patterns
Some(5) match { case Some(_) => println(“Yes”) }
Wildcard imports
import java.util._
Hiding imports
import java.util.{ArrayList => , }
Joining letters to punctuation
def bang_!(x: Int) = 5
Assignment operators
def foo_=(x: Int) { … }
Placeholder syntax
List(1, 2, 3).map (_ + 2)
_+2匿名函数 f=>f+2, f是int
List((1,1), (2,2), (3,3)) map (_._2)
f=>f._2, f是Tuple,_2表示元组的第二个元素
List(1,2,3)
val m = Map("one"->1,"two"->2,"three"->3)
m.foldLeft(0)(_+_._2)
第一个_表示取迭代前一个计算结果,
Partially applied functions
List(1, 2, 3) foreach println _
There may be others I have forgotten!
Example showing why foo() and foo are different:
This example comes from 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; 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).
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.
This may well be the trickiest gotcha in Scala I have ever encountered.
转载
http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala