[英]what's the purpose or meaning of >: in scala
Such as List.contains ,here is the source code from scala api. 例如List.contains,这是来自scala api的源代码。
def contains[A1 >: A](elem: A1): Boolean = {
var these = this
while (!these.isEmpty) {
if (these.head == elem) return true
these = these.tail
}
false
I understand the inter code theory, But what's about type A1 >: A
? 我了解内部代码理论,但是类型
A1 >: A
呢?
I guess >:
just like isInstanceOf
or something like to limit the input param's type? 我猜
>:
就像isInstanceOf
一样,还是想限制输入参数的类型?
Could some one give a concise explanation or some docs so i can get some research 可以给一个简洁的解释或一些文档,这样我就可以得到一些研究
The meaning: 含义:
A1
is the nearest common ancestor of A
and supplied argument type. A1
是A
和提供的参数类型的最接近的公共祖先。
The purpose: 目的:
since List
is declared as List[+A]
where +A
means "covariant on type A", using A
as an argument type is not allowed: 由于
List
声明为List[+A]
,其中+A
表示“类型A的协变量”,因此不允许将A
用作参数类型:
scala> :pa
// Entering paste mode (ctrl-D to finish)
class List[+A] {
def m(x: A) = x
}
// Exiting paste mode, now interpreting.
<console>:15: error: covariant type A occurs in contravariant position in type A of value x
def m(x: A) = x
UPDATE UPDATE
Naive explanation why not (just a guess, it's hard to prove since compiler won't allow it): 天真的解释为什么不这样做(只是一个猜测,由于编译器不允许,因此很难证明):
class List[+A] {
def m(x: A) = x
}
class Fruit
class Apple extends Fruit
class Pear extends Fruit
// list is covariant, which means
// List[Fruit] is a supertype of List[Apple]
val l: List[Fruit] = new List[Apple]
// i.e. l.m has to accept Fruit
l.m(new Pear) // Apple?
in reality: 事实上:
class List[+A] {
def m[A1 >: A](x: A1) = x
}
...
l.m(new Pear) // Fruit, the nearest common ancestor of Apple and Pear
A
>:
B
表示B
是A
的下限类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.