1

在 java 中,一些标准库方法(也许它们实际上不是方法?)具有以下格式:

keyword(condition or statements) {
//write your code here
}

这包括 if 语句、for-loop、while-loop do-while-loop 等。

for(initialValue = n; conditionForLoopToContinue; incrementOrDecrement) {
//write your code
}

您也可以像这样启动匿名线程:

new Thread() {
//write your code here
}.start();

我想知道的是,我们能否创建我们自己的方法(或您实际调用的任何方法)具有这种大括号格式?

因此,例如,我会编写一个“直到”方法,如下所示:

int a = 0;
until(a == 10) {
a++;
}

其中 until(a == 10) 将等价于 while(a != 10)。

当然,上面的例子不允许我们做任何新的事情(我们可以只使用一个while循环),但是这个问题的目的是找出我们是否可以编写“自定义花括号方法”。

另外,如果你们知道任何具有此功能或类似功能的语言,请告诉我。

提前感谢您的帮助!

4

3 回答 3

2

您无法实施自己的关键字。您当然可以创建自己的类的匿名子类,即您可以这样做

new YourOwnClass() {
    // write your code here
}.launch();

如果你喜欢。

使用 Java 8,您可以更进一步地了解您所要求的花括号语法。这是我尝试util使用 lambdas 模仿您的方法:

public class Scratch {

    static int a;

    public static void until(Supplier<Boolean> condition, Runnable code) {
        while (!condition.get())
            code.run();
    }

    public static void main(String[] args) {
        a = 0;
        until(() -> a == 10, () -> {
            System.out.println(a);
            a++;
        });
    }
}

输出:

0
1
2
3
4
5
6
7
8
9

请注意,在这个稍微做作的示例中存在一些限制。a 例如,由于闭包,需要是字段或常量变量。

于 2014-12-11T10:03:37.337 回答
0

实际上,您正在做的是扩展语言,即发明一个新的“保留字”并说该保留字必须后跟一个布尔表达式和一个语句(块)。

您需要一个新的保留字这一事实可能会导致很多问题,例如人们今天可能已经until在变量的上下文中使用了这个词。您的新功能会破坏该代码。

此外,您还需要告诉运行时环境您的新语句的效果是什么。

我不知道你可以简单地做到这一点的语言。就像@aioobe 所说,lambdas 可能是接近的东西。

于 2014-12-11T10:07:31.577 回答
0

不如 aioobe 的优雅:

abstract class until<T> {
    // An attempt at an `until` construct.

    // The value.
    final T value;
    // The test.
    final Function<T, Boolean> test;

    public until(T v, Function<T, Boolean> test) {
        this.value = v;
        this.test = test;
    }

    public void loop() {
        while (!test.apply(value)) {
            step();
        }
    }

    abstract void step();
}

public void test() {
    AtomicInteger a = new AtomicInteger();
    new until<AtomicInteger>(a, x -> x.get() == 10) {

        @Override
        void step() {
            a.getAndIncrement();
        }

    }.loop();
    System.out.println("a=" + a);
}

可能可以使用一些改进。

就其他语言而言。

C- 如果我没记错的话 - 你可以这样做:

#define until(e) while(!(e))

BCPL中,有一整套条件句WHILE,UNTIL等等。IFUNLESS

于 2014-12-11T10:58:46.063 回答