Kotlin. How do you expand enum?



  • Background.

    With help retrofit I'm pulling out of the server. json♪ That's it. json a very large set of status-type parameters, as set in integer

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

    Each of the "statuss" is described by the relevant enum and filled with help GSONConverterFactory with a bunch of adapters connected integer Total @SerializedName You won't.

    Well, that's what I' in every one of these. enum such function is present

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

    There's nothing in the paradigm of reusing the code.

    That's the question, how can this function be carried out so that it's one for everyone?

    Nyuance, if the value was not found, some default meaning should be returned, but it could be simple. Exception It's not a good thing to leave, but I don't think that's a situation.

    Something like that comes into the head.

    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's quite expected to fight the impossibility. Т containment companion object



  • That's what just came to mind.
    Put an extension on java class enum-a.

    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 is to determine what to return as a default point. I have the highest value of every enum. One last thing.

    But you can do that.

    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
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2