scala - `contains[BB >: B](e: BB): Boolean` 而不是 `contains(e: Any): Boolean` 的好处

标签 scala standard-library either

contains 定义为 contains[BB >: B](e: BB): Boolean 而不是 contains(e: Any) 有什么好处: Scala 中的 bool 值

Either.contains在 Scala 标准库中使用第一个签名,我不清楚这种签名相对于第二个签名的好处。

最佳答案

在这种情况下,无:两个签名是等价的。但它提供了与其他成员签名的一致性,例如

 getOrElse[BB >: B](or: ⇒ BB): BB

对他们来说,这是有区别的,因为 BB 是返回类型的一部分,所以如果我们传递一个 B,我们得到 B返回,我们不会使用 getOrElse(or: => Any): Any

What boggles me is why you would ever want to pass something that's not a B to that function

你不会。但是 contains(e: B) 不允许 Either 协变。试试吧,编译器会以B出现在逆变位置为由拒绝它。协方差意味着例如Either[A, SubtypeOfFoo]Either[A, Foo] 的子类型。所以任何对 Either[A, Foo] 合法的调用也必须对 Either[A, SubtypeOfFoo] 合法,这包括 contains(Foo).

关于scala - `contains[BB >: B](e: BB): Boolean` 而不是 `contains(e: Any): Boolean` 的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44741964/

相关文章:

scala - 如何初始化具有多个操作的字段?

c++ - 标准对初始化

Scala 要么 : simplest way to get a property that exists on right and left

c++ - 关于auto_ptr的一个问题

scala - 要么单元操作

c++ - 在模板类上重载运算符

scala - 从字符串中删除多种字符类型

scala - 在scala中实现长轮询并用akka玩2.0

scala - `.get(“key” )` on a `选项[Map [String,String]]`如何工作

python - 为什么 "they"选择引发异常?