https://kotlinlang.org logo
Title
d

dave08

04/22/2018, 2:34 PM
Hi guys! Is there any way of to implement
invoke
operator to initialize an
enum class
? I tried as an extension function, but the Intellij doesn't seem to see the constructor...
k

kingsley

04/22/2018, 2:38 PM
What do you mean “initialize an enum class”
d

dave08

04/22/2018, 2:40 PM
enum A() { B, C }

operator fun A.invoke(s: String) = if (s == "something") A.B  else A.C
Then I would call
A("something")
k

kingsley

04/22/2018, 2:42 PM
Your operator is defined on instances of A, so it would require an already available instance. To call something like
A("something")
, you need either to use the companion object invoke, or a factory function:
fun A(s: String) = if (s == "something") A.B else A.C
d

dave08

04/22/2018, 2:45 PM
Oh, that makes sense! I guess that was a confusion because extension functions are essentially
static
members, but forgot they're called on the actual instance... 🙈. Thanks for the explanation!
👍 1