我想了解 Java 的“更新”语法和 API 中的可能性。更新我的意思是 10+(比如说 10-13)。它主要是围绕 lambdas 的声明和存储符合与映射中的值相同的签名的不同实现。最近我主要与 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);
}
我的问题:
- 是否可以在没有命名接口的情况下以类似于 Gosu 的“匿名”功能方式完成?
- 还有什么可以让Java更简洁的吗?
更新:这只是围绕代码进行的一些游戏,其目的是将原始 long 双重转换为较小的类型并返回。灵感来自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);
});
}
}