https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Colton Idle

10/02/2020, 2:31 AM
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?
r

Ruckus

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
n

nanodeath

10/02/2020, 5:17 AM
false, extension methods are the best alternative 🙃
🧌 2
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
r

Ruckus

10/02/2020, 5:21 AM
@elizarov wrote an excellent article a while back about how extensions can provide an interesting paradigm shift. I'd highly recommend reading it if you haven't: https://medium.com/@elizarov/extension-oriented-design-13f4f27deaee
c

Colton Idle

10/02/2020, 6:28 AM
I have not. Thank you.
t

Tobias Berger

10/02/2020, 9:08 AM
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
object
to provide more context on the call side.
👍 1
2 Views