Java 在什么是“静态”和什么是“动态”之间有严格的划分,并且没有提供一种语言结构来混合两者。
如果您想要一个“动态范围”的值,则将其转换为在运行时评估的对象/方法。
例如,这些示例在Are Java 8 Lambdas Closures 中提供?(阅读完整说明):
Python
# Closures.py
def make_fun():
# Outside the scope of the returned function:
n = 0
def func_to_return(arg):
nonlocal n
# Without 'nonlocal' n += arg produces:
# local variable 'n' referenced before assignment
print(n, arg, end=": ")
arg += 1
n += arg
return n
return func_to_return
x = make_fun()
y = make_fun()
for i in range(5):
print(x(i))
print("=" * 10)
for i in range(10, 15):
print(y(i))
""" Output:
0 0: 1
1 1: 3
3 2: 6
6 3: 10
10 4: 15
==========
0 10: 11
11 11: 23
23 12: 36
36 13: 50
50 14: 65
"""
Java(不允许使用“动态范围”)
// AreLambdasClosures.java
import java.util.function.*;
public class AreLambdasClosures {
public Function<Integer, Integer> make_fun() {
// Outside the scope of the returned function:
int n = 0;
return arg -> {
System.out.print(n + " " + arg + ": ");
arg += 1;
// n += arg; // Produces error message
return n + arg;
};
}
public void try_it() {
Function<Integer, Integer>
x = make_fun(),
y = make_fun();
for(int i = 0; i < 5; i++)
System.out.println(x.apply(i));
for(int i = 10; i < 15; i++)
System.out.println(y.apply(i));
}
public static void main(String[] args) {
new AreLambdasClosures().try_it();
}
}
/* Output:
0 0: 1
0 1: 2
0 2: 3
0 3: 4
0 4: 5
0 10: 11
0 11: 12
0 12: 13
0 13: 14
0 14: 15
*/
Java(将值转换为对象以进行运行时评估,即“动态范围”)
// AreLambdasClosures2.java
import java.util.function.*;
class myInt {
int i = 0;
}
public class AreLambdasClosures2 {
public Consumer<Integer> make_fun2() {
myInt n = new myInt();
return arg -> n.i += arg;
}
}