Code vibe check
from Lojcs@piefed.social to programming@programming.dev on 24 Nov 12:16
https://piefed.social/c/programming/p/1505908/code-vibe-check

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];  
}  

#programming

threaded - newest

6nk06@sh.itjust.works on 24 Nov 12:21 next collapse

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.social on 24 Nov 12:24 collapse

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

HelloRoot@lemy.lol on 24 Nov 13:30 next collapse

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.

Kissaki@programming.dev on 24 Nov 15:08 next collapse

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.

Lojcs@piefed.social on 24 Nov 16:01 collapse

Yeah pretty much as you said. I tried overriding ?[] to make it more clear but apparently ? operators can’t be overriden.

I think I’ll go for .callMaybe()

FishFace@piefed.social on 24 Nov 17:16 collapse

Don’t overload things if the semantics don’t match. You’re not accessing something in a container; you’re calling a function.