Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Anonymous class

In general, D implements anonymous classes like java does it. The difference is access to final variables for the instanciating method. In Java the anonymous class can access local variable or parameter of the instanciating method, if they are final. This is in fact like they are constant values in the anonymous class. In D this would compile without error, but has another semantic. In D, the anonymouse class would get the context pointer of the instanciating method. If the method ends the local vars of the method do not exist any longer. But the reference to the created object is often stored. If the object is later called, and tries to access the local var of the instanciating method, the program will crash.

A way to solve this is, to make fields in the anonymous class, which store the values from the instanciating method, in the moment of creation. That implies, TioPort has to find all those variables and add matching parameters in the ctor, and fields into the class. The ctor must be created and copy the values into the fields.

Rewriting the class to an explicit inner class would not be necessary, but make no difference. In developement of TioPorts?, this helps to find all references to method local variables, because the D compiler will throw an error after the rewrite if the var was not detected and supplied as field.