Last active
October 27, 2015 06:26
-
-
Save sshark/49432fa959a74e0adf68 to your computer and use it in GitHub Desktop.
Containers with generics
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 acme.jelly; | |
| public class Apple extends Fruit {} | |
| package acme.jelly; | |
| public class Box<T extends Fruit> { | |
| private T item; | |
| public Box(T item) { | |
| this.item = item; | |
| } | |
| public T get() { | |
| return item; | |
| } | |
| public void replace(T item) { | |
| this.item = item; | |
| } | |
| } | |
| package acme.jelly; | |
| public class Fruit {} | |
| package acme.jelly; | |
| public class RealBox<T> { | |
| private T item; | |
| public RealBox(T item) { | |
| this.item = item; | |
| } | |
| public T get() { | |
| return item; | |
| } | |
| public void replace(T item) { | |
| this.item = item; | |
| } | |
| } | |
| package acme.jelly; | |
| public class RunMe { | |
| public static void main(String[] args) { | |
| RealBox<? extends Fruit> box = new RealBox<>(new Apple()); | |
| System.out.println(box.get()); | |
| // box.replace(new Apple()); // will fail compilation | |
| // System.out.println(box.get()); // will fail compilation | |
| } | |
| } |
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 Plant | |
| class Fruit extends Plant | |
| class Apple extends Fruit | |
| // 'var' is not allowed for covariant type | |
| // class RealBox[+T](var item: T) { | |
| class RealBox[+T](item: T) { | |
| def get: T = item | |
| def getOrElse[U >: T](otherItem: U, really: Boolean): U = | |
| if (really) item else otherItem | |
| // Not allowed for covariant type | |
| // def replace(item: T): Unit = this.item = item | |
| } | |
| class Box[T <: Fruit](var item: T) { | |
| def get: T = item | |
| def replace(item: T): Unit = this.item = item | |
| } | |
| //val appleBox = new RealBox(new Apple) | |
| //val plantBox = new Box[Plant](new Plant) | |
| val appleBox = new Box(new Apple) | |
| appleBox.get // do not use println in worksheet | |
| val fruitRealBox = new RealBox[Fruit](new Fruit) | |
| fruitRealBox.getOrElse("aa", false) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment