Skip to content

Instantly share code, notes, and snippets.

@emmanueltouzery
Last active March 11, 2017 11:14
Show Gist options
  • Save emmanueltouzery/848b9f8ae163acf87c113f4abdcbd5bf to your computer and use it in GitHub Desktop.
Save emmanueltouzery/848b9f8ae163acf87c113f4abdcbd5bf to your computer and use it in GitHub Desktop.
import javaslang.collection.*;
import javaslang.*;
public class SetNarrowTest {
static class PersonBase {
public final String name;
public PersonBase(String name) {
this.name = name;
}
@Override
public boolean equals(Object other) {
return other instanceof PersonBase &&
((PersonBase)other).name.equals(name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
static class Person extends PersonBase {
public final int age;
public Person(String name, int age) {
super(name);
this.age = age;
}
@Override
public boolean equals(Object other) {
return other instanceof Person &&
((Person)other).name.equals(name) &&
((Person)other).age == age;
}
@Override
public int hashCode() {
return Tuple.of(Integer.toString(age), super.hashCode()).hashCode();
}
}
public static void main(String[] argv) {
final Set<? extends PersonBase> persons = HashSet.of(new Person("a", 1), new Person("a", 2));
System.out.println(persons.size());
final Set<PersonBase> personBases = Set.narrow(persons);
System.out.println(personBases.size());
}
}
@danieldietrich
Copy link

Thank you! Yes, that's our use-case and it looks alright. Maybe something obscure can occur when mixing instances of PersonBase and Person in that Set, but that would be an error by itself and has nothing to do with narrowing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment