Generic method reference type specifying before/after :: operator

snr :

What is the difference between the following method references,

BiPredicate<List<String>,String> contains1 = List<String>::contains;

BiPredicate<List<String>,String> contains2 = List::<String>contains;

BiPredicate<List<String>,String> contains3 = List<String>::<String>contains;

Do the cases have special names? Is there any example similar to the usage?

Eugene :

First of all, that is called a type witness (in the official Oracle Tutorial) or TypeArguments (in the JLS Sec 15.12) and you are effectively helping the compiler with such constructs.

One example:

private static void test(Callable<Object> call) {

}

private static void test(Runnable run) {

}

static class Gen<T> {

}

And call it via test(Gen::new); (this will fail, never mind why), but the point is that you add a type witness to help the compiler, so this would work

test(Gen<String>::new);

So when you write List<String>, you have added a type witness for the target type - List that is; in the second case you are adding one for the method contains - but it's not generic, so it is ignored.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35567&siteId=1