Implementing a factory via the invoke() function of a companion object at the top of a sealed hierarchy

62 Views Asked by At

Consider I have a sealed type hierarchy in Kotlin, i.e. I'm the only one who controls how exactly a particular interface is implemented and how may implementations it has:

sealed interface Foo {
    val state: Int

    fun doSmth()
}

Now, there goes an implementation which I'd rather not expose to the clients of my API, hence marking it as internal:

internal data class FooImpl internal constructor(override val state: Int) : Foo {
    override fun doSmth() {
        // ...
    }
}

Now I need to implement a factory, and I do so directly in the companion object of my interface:

sealed interface Foo {
    // ...

    companion object Factory {
        operator fun invoke(state: Int): Foo = FooImpl(state)
    }
}

My clients will be instantiating the interface like this, knowing nothing about the actual implementation:

val foo: Foo = Foo(42)

Now, despite this code may look like a clever idea, the question is: what disadvantages it may have?

I've searched JetBrains repositories at GitHub, and despite I did find several matches, their number is few. I'm wondering whether the above code is a known anti-pattern.

0

There are 0 best solutions below