Skip to content

Instantly share code, notes, and snippets.

@sshark
Last active October 27, 2015 06:26
Show Gist options
  • Select an option

  • Save sshark/49432fa959a74e0adf68 to your computer and use it in GitHub Desktop.

Select an option

Save sshark/49432fa959a74e0adf68 to your computer and use it in GitHub Desktop.
Containers with generics
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
}
}
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