https://kotlinlang.org logo
#server
Title
# server
a

Asaf Peleg

10/11/2023, 2:34 AM
Any thoughts, best practices around objects vs. top level function declarations for related but independent functions? I'm assuming there's some overhead in creating a static object but is it negligible? The benefit feels like slightly better development experience being able to have auto complete when using the functions.
j

jessel

10/11/2023, 2:36 AM
I don’t imagine there’s any meaningful performance difference between the two - top level variables and functions within Kotlin essentially get compiled into an invisible object, since the JVM itself doesn’t really support top level anything but classes
e

ephemient

10/11/2023, 2:40 AM
Kotlin
object
compiles to a class with a singleton object instance whereas top-levels compile to static fields and methods, so it's not quite the same
there should be no noticeable performance difference though
technically Java sort of allows top-levels now: https://openjdk.org/jeps/445 (not in a way that's useful for Kotlin though)
a

Asaf Peleg

10/11/2023, 2:43 AM
thanks for chiming in
Aggregate internet answer seems to be "it's up to you" since it doesn't affect performance much. Opinions seems to come down to style/preference. Pro Object: • Namespacing, easier to control pollution for auto-completion. Pro Top Level: • Slightly better performance • Kotlin may add namespacing in future
e

ephemient

10/11/2023, 2:50 AM
in general, I lean towards top-level functions. the package name itself is already a namespace, and that's what stdlib does too
👍 4
oh and https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-typography/. but IMO Charsets and Typography are a bit different since they're holding constants
a

Asaf Peleg

10/11/2023, 3:01 AM
I think those exceptions illustrate that there's potentially a use case for both
3 Views