为什么scala List可以将covariant类型作为方法+ =中的参数

时间:2015-12-12 10:15:38

标签: list scala covariant

Scala List声明为

// Your array with name of tables initially read from your zip 
$tableNameArr = ... 

var_dump($tableNameArr); // to make sure data read from zip properly 

// Store here items in this format `key` should be after `value`
// E.G. if `BPStock` should be after `BPTran` in your case then
$afterItemsArr = array('BPStock' => 'BPTran', .. other values.. );

foreach($afterItemsArr as $key => $value){

    $key_index = array_search( $key, $tableNameArr);
    $value_index = array_search( $value, $tableNameArr);

    // if value(BPTran) index is more then index of key(BPStock)
    // then replacing their places in $tableNameArr
    if($value_index > $key_index){
       $c = $tableNameArr[$value_index];
       $tableNameArr[$value_index] = $tableNameArr[$key_index];
       $tableNameArr[$key_index] = $c;
    }
}

var_dump($tableNameArr); // to make sure data is ok

将元素添加到List的方法声明为

sealed abstract class List[+A] extends AbstractSeq[A] with LinearSeq[A] with     Product with GenericTraversableTemplate[A, List] with LinearSeqOptimized[A, List[A]] with java.io.Serializable

由于A类是协变的,为什么编译器不会抱怨,因为A出现在+ :?

的逆变位置

1 个答案:

答案 0 :(得分:3)

因为它的完整签名是:

def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That

您在问题中提到的文档只是简化文档,您需要检查方法的完整签名。