Wrote this to reduce boilerplate when calling a function with a nullable parameter. Language is Dart. I like how concise it is but it feels weird to override []. Would you be okay with this?

extension CallMaybe<R, T> on R Function(T t) {  
  R? callMaybe(T? t) => switch (t) {  
    null => null,  
    T t => this(t),  
  };  

  R? operator [](T? t) => callMaybe(t);  
}  

void example() {  
  int? n;  
  math.sqrt[n];  
}  
  • 6nk06@sh.itjust.works
    link
    fedilink
    arrow-up
    12
    arrow-down
    1
    ·
    2 days ago

    I wouldn’t use this and most people will forget that it exists. Most of the time you have do use the language and avoid hacks like that.

    Don’t you have alternatives in Dart?

    • Lojcs@piefed.socialOP
      link
      fedilink
      English
      arrow-up
      3
      ·
      2 days ago

      I don’t think so, the null aware operator doesn’t rescue the nullable out of the parameter list.