by ninkendo · 3y ago · 0 comments
In swift, there's some nice quasi-laziness you can add to function parameters, so that (say) a logging function that can fully skip evaluating a string sent to it with the `@autoclosure` syntax:
func log(message: @autoclosure () -> String, level: Level = .info) {
guard level >= configuredLevel else {
return
}
actuallyLog(message())
}
And call it like: log(message: "User is \(someExpensiveFunction(user))", level: .debug)
And if the configured log level does not include debug messages, `someExpensiveFunction(user)` doesn't get called.This works because @autoclosure lets you take a parameter that is "function returning String", but callers can just pretend they're passing it a String, without having to decorate it in a function. The compiled code will turn it into a closure behind the scenes, and thus it'll be evaluated lazily.
Not sure if there's any way to do something like this in Java with this proposal...
void log(Supplier<? extends String> messageSupplier);
log(() -> log.info"User is \{someExpensiveFunction(user)}");
The pattern of using Supplier to provide a lazy argument is pretty well-established afaict. new Object() { public String toString() { return
<actual expression here>
; } }
You can wrap that into a helper function that takes a lambda, so you can write STR."\{lazy(() -> <actual expression here>)}" Supplier<T>Since the string template interface is untyped (parameters are arbitrary Objects), having case distinctions based on the type parameter is fiddly. What if you pass an instance of a class that has a genuine toString() but also happens to implement Supplier<Foo> for some reason? Or if you pass a Supplier<Supplier<Foo>>, will it recurse? What if you pass a Callable or a Future? Will those work as well? This only creates the opportunity for opaque “magic” behavior.
log.info(() -> STR."template \{here}");