Somewhat Minimal example:
void main() {
A hey = A('hi');
B yo = B(5);
yo.cloner(hey.nameModifier);
hey.nameGetter();
}
class A {
String _name;
A(this._name);
void nameModifier() {
_name = " there!";
}
void nameGetter() {
print(_name);
}
}
class B {
final int _foo;
B(this._foo);
void cloner(Function x) {
print(_foo);
x();
}
}
This code works.
I'm curious about the low-level things going on here.
My question: Passing a function as an argument is probably not like copying the function's body, and pasting it to the destination.
for example, it is probably NOT working like this under the hood when hey.nameModifier
is supplied to cloner
as an argument:
void cloner() {
print(_foo);
_name = " there!";
}
Because _name
won't be defined under the scope of class B
, and furthermore, it is a private field of A
.
So, I guess, the context of the function and the objects it is accessing (nameModifier) are also somehow passed as references to the other function (cloner)
P.S.
If the function I was passing was not modifying some internal information like _name,
but instead performing a simple print, like print("hello world")
, I wouldn't be confused. Because print
is defined everywhere.
The question is not how to pass functions as arguments?, but how come internal information is being dereferenced in this process?.
CodePudding user response:
Each function is saved in the memory and the name of the function is used as a pointer to the location where the function is saved, think of it as using int*. when you pass the function you pass the location of the function.
So when you call that function it will run inside the A class and therefore _name will be defined.