Type Bounds中的下划线(_)有特殊含义吗?

Bil*_*ill 7 types scala existential-type type-bounds

我试图了解Scala的存在类型.

之间有什么区别:

def foo[X <: Bar] = 3
Run Code Online (Sandbox Code Playgroud)

def foo[_ <: Bar] = 3
Run Code Online (Sandbox Code Playgroud)

或者它们不仅仅是未命名的类型参数?

Rég*_*les 6

_确实只是一个未命名的类型参数,不多也不少.有什么区别def foo[_ <: Bar] = 3def foo[X <: Bar] = 3其中X未使用.

更新:

回应:"我想不出一个未使用类型的用例,我会感激一个":

请注意,这与询问如果未使用参数的目的是什么的几乎相同,例如:

def foo( x: Int ) = 123
Run Code Online (Sandbox Code Playgroud)

通常,一个很好的理由是该方法符合某些其他API中预期的形状.例如,您希望将方法(或者更确切地说是eta-expansio)传递给另一个需要参数的方法.举例:

scala> List(1,2,3).map(foo)
res0: List[Int] = List(123, 123, 123)
Run Code Online (Sandbox Code Playgroud)

另一种可能性是你的方法是一个覆盖:

trait A {
  def foo( x: Int ): Int
}

trait B extends A {
  def foo( x: Int ) = 123
}
Run Code Online (Sandbox Code Playgroud)

同样的理性适用于类型参数.以最重要的案例为例:

trait A {
  def foo[X <: Bar]: Int
}

trait B extends A {
  def foo[_<:Bar] = 3
}
Run Code Online (Sandbox Code Playgroud)

B.foo 在它的实现中不需要type参数,但它必须在那里(虽然未命名)以符合它重写的方法.