Custom Curly Bracket Methods

In java some standard library methods (Maybe they’re not actually methods?) have the following format:

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

This includes the if-statement, for-loop, while-loop do-while-loop etc.

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

Also you can start anonymus threads like so:

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

What I want to know is Can we create our own methods (or whatever you they’re actually called) that have this curly bracket format?

So , for example, I would write an ‘until’ method that goes like this:

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

where until(a == 10) would be equivalent to while(a != 10).

Of course, the example above wouldn’t allow us to do anything new (we can just use a while-loop), but the purpose of this question is to find out whether we can write ‘custom curly bracket methods’.

Also, if you guys are a aware of any language that has this feature or one similar to it, please let me know.

Thanks for any help in advance!

Answer

You can’t implement your own keywords. You can of course create anonymous subclasses of your own classes, i.e. you can do

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

if you like.

With Java 8, you get a bit further towards the curly brace syntax that you’re asking for. Here’s my attempt to mimic your util method using 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++;
        });
    }
}

Output:

0
1
2
3
4
5
6
7
8
9

Note that in this slightly contrived example there are some limitations. a for instance needs to be a field or a constant variable due to the closure.

Leave a Reply

Your email address will not be published. Required fields are marked *