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