Code of "Why Java Collections Framework is a Cats & Dogs Library"
This file contains 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
// | |
// depends on javaslang-2.1.0.jar | |
// | |
import javaslang.collection.*; | |
import java.util.List; | |
import java.util.ArrayList; | |
import static javaslang.API.*; | |
public class Test { | |
public static void main(String[] args) { | |
new Test() {{ | |
immutableShowcase(); | |
mutableShowcase(); | |
}}; | |
} | |
void immutableShowcase() { | |
Seq<Dog> dogs = Vector(new Dog()); | |
// Type narrowing, pets = dogs does not compile! | |
Seq<Pet> pets = Seq.narrow(dogs); | |
// Vector(Dog, Cat) | |
println(pets.append(new Cat())); | |
// Vector(Dog) | |
println(pets); | |
// Vector(Dog) | |
println(dogs); | |
} | |
void mutableShowcase() { | |
List<Dog> dogs = new ArrayList<>(); | |
dogs.add(new Dog()); | |
// Type narrowing, pets = dogs does not compile! | |
List<Pet> pets = narrow(dogs); | |
// Heap pollution! | |
pets.add(new Cat()); | |
// [Dog, Cat] | |
println(pets); | |
// Huh!? [Dog, Cat] | |
println(dogs); | |
} | |
@SuppressWarnings("unchecked") | |
static <T> java.util.List<T> narrow(java.util.List<? extends T> list) { | |
return (java.util.List<T>) list; | |
} | |
} | |
interface Pet {} | |
class Cat implements Pet { | |
@Override public String toString() { return "Cat"; } | |
} | |
class Dog implements Pet { | |
@Override public String toString() { return "Dog"; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment