According to Android Studio, instead of doing this:
private BluetoothAdapter.LeScanCallback mCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
}
};
I can do this:
private BluetoothAdapter.LeScanCallback mCallback;
{
mCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
}
};
}
I think the second syntax option is much prettier, but I don't understand why it requires curly braces around the anonymous class instantiation. My understanding is that curly braces locally scope the enclosed code, which doesn't make a whole lot of sense to me. What am I missing?
Those brackets around field initialization are called initializer block. Everything you put inside is executed with constructor. You can execute any code within it:
class Main {
int a = 1;
int b;
{
b = 1;
System.out.println("Hello World!");
}
}
I prefer the first approach. Initializer blocks introduce unnecessary complexity and confusion. For example this is a compile error:
Object a = b.toString();
Object b = "";
While this will fail at runtime:
Object c;
Object d;
{
d = c.toString();
c = "";
}
It becomes even more complex when you add regular constructors and superclasses to the mix.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments