Type Bounds中的下划线(_)有特殊含义吗? [英] Is there special meaning to an underscore (_) in Type Bounds?

查看:91
本文介绍了Type Bounds中的下划线(_)有特殊含义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to understand Scala's existential types.

两者之间是否有任何区别

Is there any difference between:

def foo[X <: Bar] = 3

def foo[_ <: Bar] = 3

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

or are they something more than just unnamed type parameters?

推荐答案

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

Here _ is indeed just an unnamed type parameter, no more, no less. There is no difference between def foo[_ <: Bar] = 3 and def foo[X <: Bar] = 3 where X is unused.

更新:

针对:我想不出一个未使用类型的用例,我将不胜感激":

In response to: "I can't think of a use case for an unused type, I'd be grateful for one":

请注意,这与询问是否不使用参数的目的大致相同,例如:

Note that this is pretty much the same as asking what is the purpose of having an argument if it is not used, such as in:

def foo( x: Int ) = 123

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

Usually a good reason for this is that the method conforms to a shape that is expected in some other API. By example, you want to pass the method (or rather its eta-expansio) to a another method that expects a parameter. By example:

scala> List(1,2,3).map(foo)
res0: List[Int] = List(123, 123, 123)

另一种可能性是您的方法是替代方法:

Another possibility is that your method is an override:

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

trait B extends A {
  def foo( x: Int ) = 123
}

相同的理由适用于类型参数.通过示例说明这种情况:

The same rational applies for type parameters. By example for the overriding case:

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

trait B extends A {
  def foo[_<:Bar] = 3
}

B.foo在其实现中不需要type参数,但必须存在(尽管未命名)才能符合其要覆盖的方法.

B.foo does not need the type parameter in its implementation, but it has to be there (though unnamed) to conform to the method it is overriding.

这篇关于Type Bounds中的下划线(_)有特殊含义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆