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];  
}  
you are viewing a single comment's thread
view the rest of the comments
[–] 4 points 11 months ago (1 child)

So you're using [] as an alternative function call syntax to (), usable with nullable parameters?

What's the alternative? let x = n is null ? null : math.sqrt(n);?

In principle, I like the idea. I wonder whether something with a question mark would make more sense, because I'm used to alternative null handling with question marks (C#, ??, ?.ToString(), etc). And I would want to see it in practice before coming to an early conclusion on whether to establish as a project principle or not.

math.sqrt?() may imply the function itself may be null. (? ) for math.sqrt(?n)? 🤔

I find [] problematic because it's an index accessor. So it may be ambiguous between prop or field indexed access and method optional param calls. Dunno how that is in Dart specifically.

  • source
  • hideshow 1 child comment