ey dee ey em
ey dee ey em

Reputation: 8623

what is the benefit of having an object of interface itself declare inside the interface for kotlin

for example

An interface of

interface StateInterface {

    val variationTypes: List<VariationType>
        get() = emptyList()

    object EMPTY : StateInterface
}

then its been declared inside an actionbean like this

open val stateInterface: StateInterface = StateInterface.EMPTY

Is it all it does it just create a new interface? Why we need to do it this way?

Upvotes: 1

Views: 40

Answers (1)

weston
weston

Reputation: 54811

You don't need to do it that way.

interface StateInterface {

    val variationTypes: List<VariationType>
        get() = emptyList()

}

object EMPTY : StateInterface

Would work fine, but the author decided that they wanted the usage to read StateInterface.EMPTY and not just EMPTY.

One advantage or reason for choosing this way is that EMPTY appears in the code completion after typing StateInterface. making it easier to find.

Code Completion

Another readability advantage is that anyone who references StateInterface.EMPTY does not need an additional import line which they would if it wasn't a nested object.

import com.example.StateInterface

val x = StateInterface.EMPTY

This bit open val stateInterface: StateInterface = StateInterface.EMPTY is a property on an object. It's open so descendant implementations can override it. If they do not, StateInterface.EMPTY will be the value of this property.

Upvotes: 3

Related Questions