【问题标题】:Custom Curly Bracket Methods自定义花括号方法
【发布时间】:2023-03-25 20:06:02
【问题描述】:

在 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循环),但是这个问题的目的是找出我们是否可以编写“自定义花括号方法”。

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

提前感谢您的帮助!

【问题讨论】:

  • 当然你可以拥有自己的方法并像这样格式化它,但是你的until例子不是一个自己的方法,它是尝试创建一个新的关键字。
  • if、while 等是在语言中构建的,而不是实际功能。您的 Thread() 示例是一个新的(匿名)对象。

标签: java curly-brackets


【解决方案1】:

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

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

如果你喜欢。

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

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 例如由于闭包需要是字段或常量变量。

【讨论】:

  • 很像我想出的——但更优雅。我为a 使用了泛型,但这可能不适用于您的。
【解决方案2】:

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

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

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

我不知道你可以简单地做到这一点的语言。就像@aioobe 说的那样,lambdas 可能会很接近。

【讨论】:

    【解决方案3】:

    不如 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 中有全套条件句WHILEUNTILIFUNLESS 等等。

    【讨论】:

    • 这有一个限制,即您的条件取决于单个变量。 (顺便说一句,您可以改用 Predicate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多