Mehedi Hasan Faysal
Mehedi Hasan Faysal

Reputation: 91

How do I initialize a method so that I can use it in another method as an argument?

How should I initialize the method 'greet ()' so that I can use it as an argument in 'print()'?

My code is below:

 class Person {
            var myName = 'Mehedi';
            var myAge  =   26;

            void greet() {
                print('Hi, I am ' + myName + ' and I am ' + myAge.toString() + ' years old!');
               //How do I see the above line as an Output?
            }
        }

        void main() {
            var myself = Person();
            print(myself.myName);
            print(greet()); //this is showing as an error :(
        }

Upvotes: 0

Views: 103

Answers (1)

Kris
Kris

Reputation: 3361

I think the easiest way to do what you are trying to do is just call greet directly since it already contains the print() method in it. So when you call greet(), the print() method inside will run.

void main() {
        var myself = Person();
        print(myself.myName);
        greet();
    }

alternatively you could define greet so that it returns the string instead of calling print itself:

        String greet() {
            return 'Hi, I am $myName and I am ${myAge.toString()} years old!';
        }

That way, when you call it inside the print method in main, it return a string that can be printed to the console instead of returning 'void'.

When you define greet(){ ... } you actually are defining greet as an object, as everything in dart is an object. This object happens to be a function. So you can say print(greet), without the parentheses, and it will tell you that it is an instance of a function or a closure, which is a type of function. But as soon as you put the parentheses after greet you are telling Dart to execute that function. When the function is executed, it will return something that will be the argument print uses. The compiler knows that greet() returns void and it knows print can't take void as an argument, which is why you get the error.

Upvotes: 2

Related Questions