This is a slightly abstract question about finding a pretty design approach with minimal boilerplate.
Prerequisites:
enum class Provider { Google, Microsoft }
interface Foo { fun getMail(): Mail }
that will be implemented for each specific provider.I was curious if there is a way to define ENUM class Provider
in such way that it’s implementing interface Foo
and I can later specify by which objects each concrete provider will be implemented?
I wonder if there can be a boilerplate-less way to define enum class of concrete interface while I can later define by which objects concrete provider will be implemented.
Prerequisites aren’t solid so if a better design requires changes then I’m eager for a better suggestion.
In Kotlin, you can also have enums implement interfaces. In such cases, each data value of enum would need to provide an implementation of all the abstract members of the interface. While calling these interface methods, we can directly use the enum value and call the method.
Kotlin enums are classes, which means that they can have one or more constructors. Thus, you can initialize enum constants by passing the values required to one of the valid constructors. This is possible because enum constants are nothing other than instances of the enum class itself.
We can add functions to a companion object to make them work as “static” functions. This is because the properties and functions within the companion object can be accessed with the class name, such as ClassName. functionName(). As we've seen, we've created two simple functions in the companion object body.
The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
Yep
You can make the enum implements the interface.
enum class Provider(val mail: Mail) : Foo {
Google(googleMail),
Microsoft(microsoftMail);
override fun getMail(): Mail = mail // Or this.mail
}
interface Foo { fun getMail(): Mail }
Then you access
Provider.Google.getMail()
Other way is using val members
interface Foo { val mail: Mail }
enum class Provider(override val mail: Mail) : Foo {
Google(googleMail),
Microsoft(microsoftMail)
}
And access
Provider.Google.mail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With