Is using get() not as an attribute getter a good practice?

Hello, Is it a bad practise to use get() not exactly as an attribute getter, but as a val inside a companion object ?

Something like this:

class Foo() {

fun method() {
     server.start()
}

companion object {
    private val server get() = generateANewServer()
}
}

Instead of

class Foo() {

fun method() {
     newServer().start()
}

companion object {
    private fun newServer() = generateANewServer()
}
}

Thanks!

When to use a property vs a function is one of the topics mentioned in the Kotlin coding conventions:

Prefer a property over a function when the underlying algorithm:

  • does not throw

  • is cheap to calculate (or cached on the first run)

  • returns the same result over invocations if the object state hasn’t changed

If generateANewServer isn’t a cheap function, or cached as some kind of singleton, or returns the same server, then I wouldn’t declare it as a property.

2 Likes