我想学习Java的“更新”语法和API中的可能性。较新的意思是10+(假设10-13)。 它主要围绕lambda的声明,并存储不同的实现,这些实现遵循与映射中的值相同的签名。 最近,我主要与Gosu合作,因此我可以提供以下代码段:
var longInput = 10000000L
new LinkedHashMap<String, block(long) : long>( {
"byte" -> (\x -> x as byte as long),
"short" -> (\x -> x as short as long),
"int" -> (\x -> x as int as long),
"long" -> (\x -> x as long as long)
}).eachKeyAndValue(\key, value ->
print("${longInput} ${value(longInput) == longInput ? "can" : "cannot"} be converted to ${key}")
)
我可以在Java 10中类似地进行操作:
import java.util.*;
public class Test {
public static void main(String[] args) {
long longInput = 10000000L;
var conversions = new LinkedHashMap<String, Conversion<Long>>();
conversions.put("byte", (x) -> (long) (byte) x.longValue());
conversions.put("short", (x) -> (long) (short) x.longValue());
conversions.put("int", (x) -> (long) (int) x.longValue());
conversions.put("long", (x) -> (long) (long) x.longValue());
conversions.forEach((key, value) -> {
System.out.printf("%d %s be converted to %s%n", longInput, value.convert(longInput) == longInput ? "can" : "cannot", key);
});
}
}
interface Conversion<T> {
T convert(T input);
}
我的问题:
更新: 这只是围绕代码的一些尝试,目的是对原始类型进行长时重复转换为较小的类型,然后返回。受https://www.hackerrank.com/challenges/java-datatypes/problem的启发。因此,从我的角度来看,我想留下。
使用答案,我当前的Java 10代码如下所示:
public class Test {
public static void main(String[] args) {
var longInput = 10000000L;
new LinkedHashMap<String, UnaryOperator<Long>>() {{
put("byte", (x) -> (long) (byte) x.longValue());
put("short", (x) -> (long) (short) x.longValue());
put("int", (x) -> (long) (int) x.longValue());
put("long", (x) -> (long) (long) x.longValue());
}}.forEach((key, value) -> {
System.out.printf("%d %s be converted to %s%n", longInput, value.apply(longInput) == longInput ? "can" : "cannot", key);
});
}
}
答案 0 :(得分:6)
是否可以在没有命名接口但类似的情况下完成 像Gosu中的“匿名”功能方式?
Java已经具有与您定义的相似的FunctionalInterface。您可以在UnaryOperator<Long>
中使用Map
的值。
还有什么可以使Java更简洁的了?
我认为这样会更好看:
Map<String, UnaryOperator<Long>> conversions = new LinkedHashMap<>();
conversions.put("byte", a -> (long) a.byteValue());
conversions.put("short", a -> (long) a.shortValue());
conversions.put("int", a -> (long) a.intValue());
conversions.put("long", a -> a); // UnaryOperator.identity()