Трудно объяснить этот вопрос словами. Поэтому я написал пример кода ниже для дальнейшего разъяснения. < /P>
Код: Выделить всё
//Case 1
@FunctionalInterface
interface Test {
void returnValue(R takes);
}
static R test(Test test) {
//... Do something with test
}
public static void main(final String[] args) {
test((a) -> System.out.println("called"));
//This call will always return an Object
//This is clear. It is totally unknown which type a has at compile-time
}
//--------------------------------------------------------------------------
//Case 2
@FunctionalInterface
interface Test {
R returnValue();
}
static R test(Test test) {
//... Do something with test
}
public static void main(final String[] args) {
test(() -> " ");
//This call will always return a String
//This is clear. R is specified to be a String by the return value.
}
//--------------------------------------------------------------------------
//Case 3
@FunctionalInterface
interface Test {
R returnValue(R takes);
}
static R test(Test test) {
//... Do something with test
}
public static void main(final String[] args) {
test((a) -> " ");
//This call will always return an Object
//This it not clear. R is specified to be a String by the return value
//Why doesn't it return a String ?
}
< /code>
[b] edit: < /strong>
углубляется в проблему, которую я заметил, что проблема действительно возникает только при вызове с цепками. Приведенный ниже код демонстрирует это. Он был составлен в Eclipse с использованием Java версии 1.8.0_73. < /P>
package test;
public class TestLambdaGenerics {
@FunctionalInterface
interface Test {
R returnValue(R takes);
}
static Test test(final Test test) {
// ... Do something with test
return test;
}
public static void main(final String[] args) {
final Test t = test((a) -> " ");
// Above works fine
final String t2 = test((a) -> " ").returnValue(" ");
// Above terminates with output:
// Exception in thread "main" java.lang.Error: Unresolved compilation problem:
// Type mismatch: cannot convert from Object to String
//
// at test.TestLambdaGenerics.main(TestLambdaGenerics.java:18)
}
}
Вопрос решается "с помощью цепей" с тип-инференцией просто не поддерживается Java на данный момент.
См.: Этот вопрос или эта статья
Подробнее здесь: https://stackoverflow.com/questions/362 ... on-is-pass