Created
January 1, 2012 18:42
-
-
Save notyy/1548012 to your computer and use it in GitHub Desktop.
scala covariant
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Fruit { | |
def selfIntro() = "Fruit" | |
} | |
class Apple extends Fruit{ | |
override def selfIntro() = "Apple" | |
} | |
class Package[T] (val contents:Seq[T]) { | |
def this() = this(List[T]()) | |
def putIn[T](xs:T*) = {new Package(for(x <- xs) yield x) } | |
def getAll() = contents | |
} | |
def cut(p:Package[Fruit]) {p.getAll foreach (x => Console.println(x.selfIntro + " cutted"))} | |
val fruitPackage = new Package[Fruit].putIn(new Fruit, new Fruit, new Fruit) | |
val applePackage = new Package[Apple].putIn(new Apple, new Apple, new Apple) | |
-----------------------------协变----------------------- | |
class Package[+T] (val contents:Seq[T]) { | |
def this() = this(List[T]()) | |
def putIn[U >: T](xs:U*) = {new Package(for(x <- xs) yield x) } | |
def getAll() = contents | |
} | |
---------------------------逆变完整代码------------------------- | |
class Fruit { | |
def selfIntro() = "Fruit" | |
} | |
class Apple extends Fruit{ | |
override def selfIntro() = "Apple" | |
} | |
class RedApple extends Apple{ | |
override def selfIntro() = "RedApple" | |
} | |
class Cutter[-T] { | |
def cut[U <: T](x:U) = x match { | |
case (f:Fruit) => Console.println("cut a " ++ f.selfIntro) | |
case _ => Console.println("don't know what to do") | |
} | |
} | |
class Chef[T] { | |
def cutIt(c:Cutter[T], p:T) = c.cut(p) | |
} | |
///测试结果,切红苹果的刀是不能切苹果的,而且水果的刀是可以的,这正是我们需要的 | |
scala> new Chef[Apple].cutIt(new Cutter[RedApple], new Apple) | |
<console>:16: error: type mismatch; | |
found : Cutter[RedApple] | |
required: Cutter[Apple] | |
new Chef[Apple].cutIt(new Cutter[RedApple], new Apple) | |
^ | |
scala> new Chef[Apple].cutIt(new Cutter[Apple], new Apple) | |
cut a Apple | |
scala> new Chef[Apple].cutIt(new Cutter[Fruit], new Apple) | |
cut a Apple | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment