Home > database >  Why use get on generic function
Why use get on generic function

Time:02-13

Why can you have a getter on a generic function, and how to use it?

T MyGenericFunc<T>(T x) {return x;} get what {
  print("what");
}

main(){
  var s = MyGenericFunc<String>("hey");
  print(s);
  // how to use the getter?
}

CodePudding user response:

Why can you have a getter on a generic function

"Getter on a generic function" sounds like nonsense. Your example is a getter that returns a generic function.

In most cases, you probably wouldn't want a getter that returns a function; you'd just define a function directly. For example, it's pointless to do:

num Function(num x) get square {
  return (x) => x * x;
}

when you instead could write:

num square(num x) {
  return x * x;
}

with no difference to callers: in either case, they'd just call, for example, square(3).

However, there can be a difference if the getter does work before the returned function is invoked. For example:

num Function(num x) get square {
  print('square');
  return (x) => x * x;
}

void main() {
  var f = square; // Prints: square
  print('Hello world!');
  var result = f(3); // Does not print.
  print(result); // Prints: 9
}

would print:

square
Hello world!
9

In contrast:

num square(num x) {
  print('square');
  return x * x;
}


void main() {
  var f = square; // Does not print.
  print('Hello world!');
  var result = f(3); // Prints: square
  print(result); // Prints: 9
}

would print:

Hello world!
square
9

In your example from your related question, the getter sets an internal flag (for what purpose, I don't know).

how to use it?

You'd call it like a function. In your example, since what is a getter that returns a generic function, you'd call it as what<DesiredType>(argument).

  •  Tags:  
  • dart
  • Related