What's the "best" alternative to writing static utility functions in java?
I know kotlin has companion objects, named companion objects, object classes, top level functions and extension functions... but a majority of the time, would you say that your XYZUtil.java turns into a whole bunch of kotlin extension functions?
10/02/2020, 5:13 AM
As always, it depends. If there was one universally "best" way, Kotlin would have any of the others. "Majority of the time" is often a terrible metric for these kinds of things as they are highly context sensitive.
But that's just my $0.02
10/02/2020, 5:17 AM
false, extension methods are the best alternative 🙃
while I agree there is no "best", extension methods are excellent for what would otherwise be static utils. or even just regular methods that get thrown into the class because it's convenient
I agree with using extension functions (in most cases 😉).
In my experience, those static utility class functions usually have one major purpose: providing functionality you wished was already present in the class, but it's missing so you implement it yourself. Extension functions are perfect for "pretending" the class has this functionality.
On the technical side: When compiling for JVM, top-level-(extension-)functions will be compiled to simple static functions with an added parameter for the receiver.
In some cases you need utility functions that don't make sense as extensions but would be better implemented as normal functions. Here - again - it depends, but esp. if the input parameters are something common like primitive types, I prefer putting functions like that into an