繁体   English   中英

Scala中>:的目的或意义是什么

[英]what's the purpose or meaning of >: in scala

例如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

我了解内部代码理论,但是类型A1 >: A呢?

我猜>:就像isInstanceOf一样,还是想限制输入参数的类型?

可以给一个简洁的解释或一些文档,这样我就可以得到一些研究

含义:

A1A和提供的参数类型的最接近的公共祖先。

目的:

由于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

天真的解释为什么不这样做(只是一个猜测,由于编译器不允许,因此很难证明):

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?

事实上:

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表示BA的下限类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM