了解Scala的_ vs. [英] Understanding scala's _ vs Any/Nothing

查看:97
本文介绍了了解Scala的_ vs.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果类具有变量类型参数,例如 Iterable [+ A] ,声明

If a class has a convariant type parameter such as Iterable[+A], is there any difference between declaring

def foo(bar: Iterable[_])

def foo(bar: Iterable[Any])

如果是一堂课具有相反类型的参数,例如 Growable [-A] ,声明

If a class has a contravariant type parameter such as Growable[-A], is there any difference between declaring

def foo(bar: Growable[_])

and

def foo(bar: Growable[Nothing])

推荐答案

绑定通用参数时,确实会有所不同。例如,如果您有

It does make a little difference when generic parameter is bounded. For example, if you had

class BoundedIterable[+A <: Something]
class BoundedGrowable[-A >: Something]

然后输入 BoundedIterable [Any] BoundedGrowable [Nothing] 都是非法的。

then type BoundedIterable[Any] and BoundedGrowable[Nothing] would be illegal.

我不知道是否还有其他区别,但可以肯定地说,您应该尽可能选择不使用通配符的变体。这是因为,实际上,声明站点类型差异的真正目的是摆脱通配符(这是使用站点差异的一种形式)。当您说 List [Any] 时,您的意思是任何内容的列表,但是当您说 List [_] 时,则你的意思是我们不知道什么清单。因此,即使在某些特定情况下它们可能等效,前者也更加清晰。

I don't know if there is any other difference, but I can say for sure that you should prefer the wildcard-less variant wherever possible. That is because, actually, the very purpose of declaration-site type variance is to get rid of wildcards (which are a form of usage-site variance). When you say List[Any] you mean "list of anything", but when you say List[_] then you mean "list of we-don't-know-what". So the former is just way more clear, even though they may be equivalent in some particular case.

这篇关于了解Scala的_ vs.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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