For some reason I can't get this to work (heavily simplified code that fails):
package com.domain {
public class SomeClass {
private static var helper:Helper = new Helper();
}
}
class Helper {
}
It compiles, but throws upon first access of SomeClass
:
TypeError: Error #1007: Instantiation attempted on a non-constructor.
at com.domain::SomeClass$cinit()
...
The non-constructor error is the compiler's awkward way of saying 'you have called a constructor for a class I have not seen yet'; if it were a bit smarter, it could check the file (compilation unit) for internal classes before complaining... mehhh
Seeing as you have given your static variable private
access, obviously you intend to only use the instance internally to SomeClass
(assumption; could be passed out as a return value).
The following solution defers creation of the static var to when the internal class is initialized i.e. when the (presumably implicit) Helper.cinit()
is invoked, rather than SomeClass.cinit()
when Helper
does not exist yet:
package com.domain {
public class SomeClass {
public function doSomething(param:*):void {
// ... use Helper.INSTANCE
}
}
}
class Helper {
public static const INSTANCE:Helper = new Helper();
}
+1 to Darren. Another option is to move the Helper
class to the top of the file
class Helper {
}
package com.domain {
public class SomeClass {
private static var helper:Helper = new Helper();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With