# 共變性（Covariance）

``class Node[T](val value: T, val next: Node[T])``

``class Fruitclass Apple extends Fruit {    override def toString = "Apple"}class Banana extends Fruit {    override def toString = "Banana"}val apple = new Node(new Apple, null)val fruit: Node[Fruit] = apple    // 編譯錯誤，type mismatch``

``class Node[+T](val value: T, val next: Node[T])class Fruitclass Apple extends Fruit {    override def toString = "Apple"}class Banana extends Fruit {    override def toString = "Banana"}val apple = new Node(new Apple, null)val fruit: Node[Fruit] = apple    // 編譯通過``

``def show(n: Node[Fruit]) {    var node: Node[Fruit] = n    do {        println(node.value)        node = node.next    } while(node != null)}val apple1 = new Node(new Apple, null)val apple2 = new Node(new Apple, apple1)val apple3 = new Node(new Apple, apple2)val banana1 = new Node(new Banana, null)val banana2 = new Node(new Banana, banana1)show(apple3)show(banana2)``

``class Node[+T](val value: T, val next: Node[T]) {    def replace(value: T) = new Node[T](value, next) // 編譯錯誤}``

val apple1 = new Node(new Apple, null)
val apple2 = new Node(new Apple, apple1)
val fruit1: Node[Fruit] = apple2
val fruit2 = fruit1.replace(new Banana)

fruit1所參考的實際上就是apple2的實例，而apple2所參考的是Node參數化為Apple後的物件，其實相當於以下的實例：
class Node[Apple](val value: Apple, val next: Node[Apple]) {
def replace(value: Apple) = new Node[Apple](value, next)
}

``class Node[+T](val value: T, val next: Node[T]) {    def replace[U >: T](value: U) = new Node[U](value, next)}val apple1 = new Node(new Apple, null)val apple2 = new Node(new Apple, apple1)val fruit1: Node[Fruit] = apple2val fruit2 = fruit1.replace[Fruit](new Banana)println(fruit2.value)       // Bananaprintln(fruit2.next.value)  // Apple``

class Node[Apple](val value: Apple, val next: Node[Apple]) {
def replace[U >: Apple](value: U) = new Node[U](value, next)
}

``class Node[+T] {    var value: T = _   // 編譯錯誤}``

class Node[+T] {
private[this] var v: T = _
def value: T = v
def value_=(v: T) { this.v = v }
}