fun f1(x) = x + 2; val f = fn : int -> int
ActiveLecture.org Warm-up exercise: What is the type of
fun f(g)(h)(x) = g(h(x))
S extends or implements T, S is
a direct subtype of T (S
<1 T)FileReader
is a subtype of InputStreamReader, Reader is a
subtype of CloseableFileReader <: Reader,
FileReader <: CloseableReader reader = new FileReader("input.txt");
FileReader[] <: Reader[]FileReader[] to method
that expects Reader[].String[] strs = { "Mary", "had", "a", "little", "lamb" };
Object[] objs = strs; // legal: String[] <: Object[]
objs[0] = new Watermelon(); // legal: Watermelon <: Object
strs[0] is a Watermelon, not a
String!ArrayStoreExceptionArrayList<File>ArrayList<File> files = new ArrayList<File>();
. . .
files.add("mydata.txt"); // Error message
ArrayList files = new ArrayList();
files.add("mydata.txt"); // No error
. . .
File file = (File) files.get(0); // ClassCastException
<T>, use type variables
public class ArrayList<T> {
private T[] values; // white lie
public T get(int i) { return values[i]; }
. . .
}
ArrayList<File>, ArrayList<String>
turn into plain ArrayList (with Object[]
values)Comparable<T> can compare
against object of type T
public interface Comparable<T> {
int compareTo(T other)
}
public class Employee implements Comparable<...> {
public int compareTo(Employee other) { return id - other.id; }
. . .
}
Comparable? ActiveLecture.orgpublic class Util {
public static <T> T max(List<T> lst) { . . . }
}
List<String> strs = . . .; String s = Util.max(strs); // infers Util.max<String>
max? Need to know that the list values
are comparablepublic static <T extends Comparable<T>> T max(List<T> lst) {
T max = lst.get(0);
for (T x : lst) if (x.compareTo(max) > 0) max = x;
return max;
}
S is a subclass of T, should
ArrayList<S> be
ArrayList<T>?ArrayList<T>?ArrayList<T>?Hint: Think about a concrete example for S and T
ActiveLecture.org
ArrayList<Manager> was a subclass of
ArrayList<Employee>
ArrayList<Manager> bosses = ...;
Employee empl = bosses.get(0); // OK, a manager is an employee
ArrayList<Employee> empls = bosses; // managers are employees
empls.add(0, new Employee("Dilbert")); // OK to add employee
bosses and empl are references to the
same collectionArrayStoreException? Object[] array to hold the
ArrayList elementsArrayList<? extends Employee>
ArrayList<? extends Employee> empls;
Employee e = empls.get(0); // OK
empls.put(new Employee("Dilbert")); // Compile-time error
public void readAll(List<? extends Reader> readers) // ok to pass ArrayList<FileReader>
? super is the opposite of ? extends ArrayList<Manager> bosses = . . .; // Manager <: Employee <: Comparable<Employee> Manager m = Util.max(bosses); // static <T extends Comparable<T>> T max(List<T> lst)
static <T extends Comparable<? super T>> T max(List<T> lst)
“A moment of convenience; a lifetime of regret”