Why "this" behaves differently when used inside a class function/method as compared to when it is used inside an anonymous function.
For example
public MyClass
{
function myfun()
{
output(this) // << will show the instance of this class but not myfun() function
abc = function ()
{
output ( this ) // << will show abc function
}
abc()
}
}
So, why "this" outputs the instance of MyClass but doesnot output myfun() . What makes it different from anonymous functions ?
While the specific will vary between languages, the general idea behind an anonymous inline method such as that is that the compiler will create a new class (possibly given some random name, just for it's own use), inside that class will be a method (again, probably given some auto-generated name for it's own use) and that method will do the work of the anonymous method. Then in the original call site of the anonymous method it creates an instance of this compiler generated class and calls the appropriate method within that class.
As such, the definition of that anonymous method is going to actually be called from within another type, not from within the type that declared the anonymous method.
Related
Even though I am familiar with singleton, Dart's factory is confusing. I have seen an existing question, but the only thing I got from the answer is that the name can be whatever identifier that starts with an _. Even though the person had asked why it should be called, the answer does not seem to be explaining that.
If I comment out the Dog._internal(); line, I get Method not found: 'Dog._internal'. It looks like calling a method, but is it like C's function prototype? But it has no return type. Can someone explain the Dog._internal(); line to me?
class Dog
{
static final Dog dog = Dog._internal();
//Dog._internal();
factory Dog()
{
return dog;
}
}
There are multiple concepts going on so lets go through the example:
factory Dog()
{
return dog;
}
This defines a factory constructor. Factory constructors are much like normal static methods but must always return an object which are compatible with the type of which the factory constructor is part of. In our example the factory constructor must return a Dog object.
It is not a constructor in that sense that we already have created a object when we enter this method. Again, it can be compared to static Dog Dog() but is allowed to override the default constructor. So we must create the object manually and return it.
This allows us to control the behavior of when objects are created and in our case allows us to have a singleton pattern so when somebody are trying to create an instance of Dog they will always get the same object.
Dog._internal();
This is called a named constructor. Constructors in Dart can have given names which makes it easier to distinguish different constructors. But also because Dart does not allows us to override methods with different number of parameters.
Also, because of the name starting with _ it means this constructor is marked private and cannot be used outside of the library it is part of. So if your code is part of a library, the code importing your library are not allowed to call your private constructor.
This is again a nifty trick to allow us to make a singleton since we don't want other than our own code to create a new instance (which are the only instance we want to create).
static final Dog dog = Dog._internal();
This is essential creating the singleton. The reason for this is that static variables in Dart are lazy-evaluated so the value dog does not really have any value before it is called. After first call, the value are "cached" so Dog._internal(7) are only called once as long our application (or more specific, our isoleate instance) are running.
I would properly call the variable _instance or _dog so it is also private.
Dog.foo(); defines a named constructor named foo that takes no arguments and has no body. It's equivalent to Dog.foo() {}. Similarly, Dog._internal(); defines a named constructor named _internal. This would be more obvious if the constructor took arguments and did work, for example:
class Dog {
static final Dog dog = Dog._internal(7);
Dog._internal(this.years) {
registerAnimal(this);
}
factory Dog() {
return dog;
}
int years;
}
I have a very simple function which I define as follows:
def mySimpleFunction(Map myMap) {
// Function logic here...
}
However, when I try to compile this, I get a warning message and build exception which says that: The [mySimpleFunction] action accepts a parameter of type [java.util.Map] which has not been marked with Validateable.
How can I mark this function as Validateable? I imported the org.codehaus.groovy.grails.validation.Validateable
and have marked my class as #Validateable .
What should I be doing differently in order to get my application to build?
Thank you in advance!
If it is a helper method, make it private. In Grails 2.0+ public controller methods are assumed to be actions, and arguments are assumed to be bindable. That means they need to be number types, boolean, String, etc., or a command object class.
Command object classes are automatically made validateable if they're defined in the controller class file, and if they're defined elsewhere they need to be annotated as #Validateable.
Since this is a helper method and not an action, just make it private (especially since it can't be called from another class anyway):
private mySimpleFunction(Map myMap) {
// Function logic here...
}
public function setAlbumTable(AlbumTable $albumTable)
{
$this->albumTable = $albumTable;
return $this;
}
I am talking about first parameter ( it's not parameter btw) looks like datatype ? what is it ? constant ? I encounter this when trying to develop app in zend framework 2
This is PHP's type hinting. It means that the first parameter to this function - $albumTable - must be an instance of the AlbumTable class or a class that inherits from it.
class Car {}
class BlueCar extends Car {}
function drive_the_car(Car $car) {}
drive_the_car(42); // error, first parameter must be an instance of Car
drive_the_car(new stdClass()); // error
drive_the_car(new Car()); // works
drive_the_car(new BlueCar()); // works
The piece of code you're showing is an example of dependency injection via setter method. The setter is passed an instance of AlbumTable and assignes this instance to a class field.
Your method is passed ONLY ONE parameter: $albumTable.
The AlbumTable before the parameter is a type hint and makes sure that only a instance of AlbumTable or a deriving class can be passed to the setter.
It forces the actual parameter ($albumTable) to be an instance of AlbumTable class. PHP will give a fatal error if anything else is passed to the function.
This is useful so you don't have to check what type of variable/object you received in order to make use of it's functions and properties.
I just started BlackBerry development and I follow some of the tutorials to become familiar with the UI objects and so on and I saw/tried this:
private MenuItem menuItemClose = new MenuItem(new StringProvider("Contacts"), 0, 0) {
public void run() {
onClose();
}
};
I have not seen this way of instantiating an object before (thinking about new MenuItem), could someone explain what is happening?
And what is the difference between instantiating objects inside method definitions and in "instance variable section" like this?
That's called an "anonymous inner class."
Anonymous inner classes are classes which are created within another class but not named. They are instantiated by their interface or abstract base class definition and given their missing implementation inline with the instantiation.
In this case, MenuItem is abstract - it's missing its run() method. You're providing the implementation of its run() method here on lines 2-4.
Take a look at this JavaWorld article for more information about the various types and uses of inner classes.
As for the second part of your question "what is the difference between instantiating objects inside method definitions and in "instance variable section" like this?" -- the difference is scope, and when the object is instantiated.
Non-static member variables with initial values are created when the object which contains them is instantiated. The initial value assignment (initialization) executes at that time as well.
Static member variables with initial values are created and initialized when the class is loaded by the VM's class loader. With eager ClassLoading, this will occur at the start of the application. With lazy ClassLoading, this will occur the first time the class is referenced by the application. I believe by default most classes that aren't part of the Java runtime are loaded lazily.
Both static and non-static member variables have object-level scope and are accessible by other objects according to their access modifier (public/private/protected).
Non-static member variables are part of an object instance, and as such they are marked for garbage collection when that instance is orphaned or goes out of scope. Static member variables are only garbage collected if the class that contains them is unloaded. This only occurs if the ClassLoader instance which loaded said class is garbage collected. See this question for more info about that.
Local variables (variables which are defined within a method) with initial values are created and initialized when that line is executed as part of normal method execution. They are marked for garbage collection (destroyed) once they go out of scope (after the method in which they're contained finishes executing).
This creates an anonymous inner class which extends MenuItem and overrides the run method. It is standard Java and has nothing to do with Blackberry.
When you define a new inner class inside the method call, it's known as an 'anonymous inner class'. Anonymous inner classes are useful when you don't really need a reference to the object after the initial method call.
final Object obj = new Object(); // Standard instantiation
System.out.println(obj); // Prints java.lang.Object#5c005c
// Anonymous inner class
System.out.println(new Object() { }); // Prints Foo$1#2500250
// Anonymous inner classes work with interfaces too
new Thread(new Runnable() {
#Override
public void run() {
// Runnable is an interface
}
}).start();
This is quite a common pattern and can be useful to define 'one-time-use' objects, perhaps at the expense of readability.
if I want to add something to the implementation of
public static function createPopUp(parent:DisplayObject,
className:Class,
modal:Boolean = false,
childList:String = null,
moduleFactory:IFlexModuleFactory = null):IFlexDisplayObject
{
return impl.createPopUp(parent, className, modal, childList, moduleFactory);
}
do I have to put all the arguments in my function declaration or does it pick them up implicitly?
Yes - ActionScript doesn't support method overloading only overriding, in which case your method's signature must exactly match that of the overridden method.
But you are trying to override a static method which is not possible in ActionScript at all. If you want something like in the code snippet create your class not inheriting anything, put a static createPopUp method inside and let it call static createPopUp method from the class you want to decorate and call your class'es static method instead of the original one.
This impossibility to sensible inherit (or inherit at all) static methods is one of the reasons why one should try to restrain from using statics as much as possible - statics take away the power of inheritance from OO languages.