Last active
December 11, 2016 03:06
-
-
Save keigoi/359bd3ae8170837d224f2250eb0ce6d0 to your computer and use it in GitHub Desktop.
Java 8 type inference
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
import java.util.function.Consumer; | |
import java.util.ArrayList; | |
public class TypeError { | |
public static <A> void let(A a, Consumer<A> f) { | |
f.accept(a); | |
} | |
public static <A> void newArray(Consumer<ArrayList<A>> f) { | |
f.accept(new ArrayList<A>()); | |
} | |
public static <A> void add(ArrayList<A> ar, A x) { | |
ar.add(x); | |
} | |
public static <A> void addAll(ArrayList<A> ar, ArrayList<A> ar2) { | |
ar.addAll(ar2); | |
} | |
public static <A> void addAll2(ArrayList<A> ar, ArrayList<? extends A> ar2) { | |
ar.addAll(ar2); | |
} | |
public static void main(String[] args) { | |
// 0. | |
let(new ArrayList<>(), l -> add(l, "abc")); // OK | |
// 1. | |
let(new ArrayList<String>(), l -> addAll(l, new ArrayList<String>())); // OK | |
// 2. | |
let(new ArrayList<>(), (ArrayList<String> l) -> addAll(l, new ArrayList<>())); // OK | |
// 3. | |
// let(new ArrayList<>(), l -> addAll(l, new ArrayList<String>())); // NG | |
// TypeError.java:25: error: method addAll in class TypeError cannot be applied to given types; | |
// let(new ArrayList<>(), l -> addAll(l, new ArrayList<String>())); // NG | |
// ^ | |
// required: ArrayList<A>,ArrayList<A> | |
// found: ArrayList<Object>,ArrayList<String> | |
// reason: inferred type does not conform to equality constraint(s) | |
// inferred: String | |
// equality constraints(s): String,Object | |
// where A is a type-variable: | |
// A extends Object declared in method <A>addAll(ArrayList<A>,ArrayList<A>) | |
// 1 error | |
// 4. | |
let(new ArrayList<>(), l -> addAll2(l, new ArrayList<String>())); // OK | |
let(new ArrayList<String>(), l -> addAll2(l, new ArrayList<String>())); // OK | |
let(new ArrayList<>(), (ArrayList<String> l) -> addAll2(l, new ArrayList<>())); // OK | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment