Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Syntactic Sugar

I ran into this block of code today, and I don't know how it works. I know how to make anonymous classes, but I'm used to seeing a method signature and not just a pair of braces. Is the code between those braces put into a static block? Does it go into the constructor? Or is it something else altogether?

conext.checking(new Expectations() {
    { // <- what does this pair of braces do?
        oneOf(alarm).getAttackAlarm(null);
    }
});
like image 366
geowa4 Avatar asked Oct 05 '10 18:10

geowa4


People also ask

What does syntactic sugar mean?

“Syntactic sugar” is a term for syntax changes in computer programming which make it easier for humans to code. There are several different types of syntactic sugar and synonyms include “syntactic saccharine” and even “candygrammar,” which is often used to describe superfluous or unhelpful “syntactic sugar” changes.

What is an example of syntactic sugar?

A common example of syntactic sugar is an augmented assignment operator, such as +=, which simplifies the expression x = x + y to the compound operation x += y.

Is for loop syntactic sugar?

for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common practice within Rust, which is to loop over anything that implements IntoIterator until the iterator returned by .

Is switch syntactic sugar?

1) Strings in Switch are syntactic sugar, no change in JVM level. 2) Internally it uses equals method to compare, which means, if you pass null it will throw java.


1 Answers

It's an instance initializer that calls the code within the context of the created object.

This is equivalent to

Expectations exp = new Expectations();
exp.oneOf(alarm).getAttackAlarm(null);
conext.checking(exp)

Whoever wrote it might have thought he was being more efficient by not declaring a variable (not true) or that it was cleaner code (I disagree).

The primary place that these initializers are useful like this is when instantiating maps, ie:

Map map = new HashMap() {{
  put("key1", "value1");   
  put("key2", "value2"); 
}};

which I think actually is slightly more readable.

like image 60
Reverend Gonzo Avatar answered Sep 20 '22 15:09

Reverend Gonzo