Skip to content

Instantly share code, notes, and snippets.

@sw-samuraj
Created May 29, 2017 20:15
Show Gist options
  • Save sw-samuraj/d451f8402e48d9f7a8e744602e5099e7 to your computer and use it in GitHub Desktop.
Save sw-samuraj/d451f8402e48d9f7a8e744602e5099e7 to your computer and use it in GitHub Desktop.
An example of the Guava ImmutableList invariance.
import com.google.common.collect.ImmutableList;
interface Powerful {}
class Jedi implements Powerful {}
class Sith implements Powerful {}
public class ImmutableListInvariance {
public static void main(String[] args) {
ImmutableList<Jedi> jedi = ImmutableList.of(new Jedi());
// ImmutableList<Powerful> powerfuls = jedi; // Error
ImmutableList<Powerful> powerfuls =
new ImmutableList.Builder<Powerful>()
.addAll(jedi)
.add(new Sith())
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment