Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin ENUM classes with common interface implemented by delegates

This is a slightly abstract question about finding a pretty design approach with minimal boilerplate.

Prerequisites:

  • I have an ENUM class for enumerating various providers i.e.: enum class Provider { Google, Microsoft }
  • Let’s say there is a service interface 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.

like image 514
kuza Avatar asked Mar 20 '18 20:03

kuza


People also ask

Can enum implement an interface in Kotlin?

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.

How does Kotlin define enum class?

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.

How can I create static method for enum in Kotlin?

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.

Can enum class have methods?

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.


1 Answers

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
like image 113
Vinicius Rangel Avatar answered Sep 17 '22 20:09

Vinicius Rangel