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];  
}  
  • HelloRoot@lemy.lol
    link
    fedilink
    English
    arrow-up
    12
    ·
    2 days ago

    overwriting [] seems like readability nightmare.

    Won’t something like this work more clearly?

    extension NullCall<T> on T? {
      R? let<R>(R Function(T) f) => this == null ? null : f(this as T);
    }
    
    void example() {  
      int? n;  
      n.let(math.sqrt);
    }  
    

    This kind of immitates Kotlin let.