Created
March 22, 2011 20:55
-
-
Save netslow/882025 to your computer and use it in GitHub Desktop.
Type variance in Scala
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
package org.halfcup.scala.learn.vary | |
class Toy{ | |
override def toString():String = { | |
"Toy" | |
} | |
} | |
class Ball extends Toy{ | |
override def toString():String = { | |
"Ball" | |
} | |
} | |
object SmallBall extends Ball{ | |
override def toString():String = { | |
"SmallBall" | |
} | |
} | |
object RedBall extends Ball{ | |
override def toString():String = { | |
"RedBall" | |
} | |
} | |
object Stick extends Toy | |
object Bone extends Toy | |
class Pet[-A,+T>:A](toy: A) { | |
override def toString():String = { | |
"Pet bring me "+toy | |
} | |
def bringMeSome():T = { | |
toy | |
} | |
} | |
class Dog[-A,+T>:A](toy: A) extends Pet[A,T](toy){ | |
override def toString():String = { | |
"Dog bring me "+toy | |
} | |
} | |
object Test { | |
def main(args : Array[String]) : Unit = { | |
val p1 = new Pet[Toy,Toy](RedBall) | |
val p2 = new Dog[Ball,Toy](new Ball) | |
val p3 = new Dog[Toy,Toy](SmallBall) | |
val p5 = new Dog[Ball,Ball](SmallBall) | |
val asdasdsad = new Pet[Ball,Toy](SmallBall) | |
// val asdasdsad2 = new Pet[Toy,Ball](SmallBall) Can't do that | |
// val p4 = new Dog[Ball,Toy](Stick) Can't do that | |
val pets = List(p1,p2,p3,new Pet[Ball,Ball](RedBall)) | |
println(pets) | |
pets.map(x => println(x.bringMeSome)) | |
var xP = p2//Dog[Ball,Toy] | |
xP = p3//Dog[Toy,Toy] | |
xP = new Dog[Ball,Ball](RedBall) | |
var iP = p3//Dog[Toy,Toy] | |
// iP = p2 Can't do that Dog[Ball,Toy] | |
var tP = new Dog[Ball,Toy](new Ball) | |
tP = new Dog[Ball,Ball](SmallBall) | |
var sP = new Dog[Ball,Ball](SmallBall) | |
// sP = new Dog[Ball,Toy](RedBall) Can't do that | |
val toysTrunk = List[Toy](p2.bringMeSome()) | |
println(toysTrunk) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment