Prehistory

With the help of retrofit pull from the json server. In this json rather large set of parameters of the type "status", given in the form of an integer .

 { "status":4, "type":7, "subType":1, "subStatus":9, и т.д. } 

Each of the "statuses" is described by the corresponding enum and is filled with a GSONConverterFactory with a bunch of connected adapters (for the integer in @SerializedName do not @SerializedName ).

Well, it turns out that I have in each of these enum there is such a function

 companion object { fun byCode(code: Int): AccidentType { for (value in AccidentType.values()) { if (code == value.code) return value } return AccidentType.UNKNOWN } } 

That does not fit into the code reuse paradigm. (with a bunch of adapters, too, everything is great, but there you will not get rid of how I understand)

So the question is, how can this function be implemented so that it is one for all?

Nuance - in case the required value was not found, it is necessary to return a certain value "by default", but you can just throw an Exception , it is not good, but, in theory, this situation cannot arise.

Something comes to mind

 fun <T:Enum<T>> enumByCode(code:Int, enum: T):T{ for (value in T.values()) { if (code == value.code) return value } return T.default } 

But it is completely expected swears at the impossibility of Т contain the companion object

    1 answer 1

    That's what just came to mind.
    Hang the extension function on the java enum class.

     fun <T : Enum<*>> Class<T>.enumByCode(code: Int): T { for (value in this.enumConstants) { if (code == value.ordinal) return value } return this.enumConstants[0] } 

    The only thing to decide what to return as the default. I have this very first value of each enum. You can last.

    But you can and so:

     enum class Unknown { UNKNOWN } fun <T : Enum<*>> Class<T>.enumByCode(code: Int): T { for (value in this.enumConstants) { if (code == value.ordinal) return value } return Unknown.UNKNOWN as T } 
    • Tomorrow I will try. So far, as a workaround I rewrote the backend to give the numbers as strings - it became possible @SerializedName use @SerializedName . But with the default trouble. I thought the interface would be general to them with the "default" method, but faced with the fact that Idea considers the interface to enum impossible - rjhdby