What are the advantages of "companion object" in properties delegating

Hi,there. I’m reading the “Programming Kotlin, By Stephen Samuel , Stefan Bocutiu”
and I’m confused by the following code in Chatper 6-Delegated properties:

interface WithId {
val id: String

data class WithIdImpl(override val id: String) : WithId

class Record(id: String) : WithId by Record.identifier(id) {
companion object Record {
fun identifier(i: String) = WithIdImpl(i)

Why don’t we declare the class like this?

class Record(id: String) : WithId by WithIdImpl(id) {}

What advantages does the former have?

Here doesn’t make any difference, you’re just inlining fun identifier.

You can run some code before retuning the WithId object, so you could construct an implementation which requires you to compute some other object.

I can’t really tell how useful or common this pattern is, I personally never used it.

1 Like

Thanks a lot.@al3c