【发布时间】:2016-07-18 00:52:12
【问题描述】:
我正在学习 Lambda,但遇到了一些我无法解决的问题。
原来我的代码是:
package Lambdas;
@FunctionalInterface
interface NumericFunc2 {
<T extends Number> T func(T n);
}
class Lbd_488_NumericFunc_SelfTest {
public static void main(String args[]) {
// This block lambda returns the smallest positive factor of a value.
NumericFunc2 smallestF = (n) -> {
double result = 1;
// Get absolute value of n.
n = n < 0 ? -n : n;
for (int i = 2; i <= n / i; i++)
if ((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " + smallestF.func(12));
System.out.println("Smallest factor of 11 is " + smallestF.func(11));
}
}
但是,我的操作员旁边不断出现错误(<、-、/)。
PS:即使我将其更改为<T extends Double>,我也会遇到同样的错误。
现在,如果我通过添加参数类型来更改代码,我会收到错误提示“目标方法是通用的”:
即使我将其更改为 <T extends Double>,我也会遇到同样的错误。
package Lambdas;
@FunctionalInterface
interface NumericFunc2 {
<T extends Number> T func(T n);
}
class Lbd_488_NumericFunc_SelfTest {
public static void main(String args[]) {
// This block lambda returns the smallest positive factor of a value.
NumericFunc2 smallestF = (Double n) -> {
double result = 1;
// Get absolute value of n.
n = n < 0 ? -n : n;
for (int i = 2; i <= n / i; i++)
if ((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " + smallestF.func(12));
System.out.println("Smallest factor of 11 is " + smallestF.func(11));
}
}
但是,如果我将类从非泛型更改为泛型,一切正常,就像下面的代码:
package Lambdas;
@FunctionalInterface
interface NumericFunc2<T extends Number> {
T func(T n);
}
class Lbd_488_NumericFunc_SelfTest {
public static void main(String args[]) {
// This block lambda returns the smallest positive factor of a value.
NumericFunc2<Double> smallestF = (n) -> {
double result = 1;
// Get absolute value of n.
n = n < 0 ? -n : n;
for (int i = 2; i <= n / i; i++)
if ((n % i) == 0) {
result = i;
break;
}
return result;
};
System.out.println("Smallest factor of 12 is " + smallestF.func(12));
System.out.println("Smallest factor of 11 is " + smallestF.func(11));
}
}
所以,我的问题是。我在代码的第一部分做什么?如何在非泛型类中正确使用具有泛型方法的 lambda?
【问题讨论】:
-
提示 - 不要在 Lambada 中的
{}内编写嘈杂的代码(超过一行),而是使用methods()