Hi! Maybe someone here knows a better way to solve...
# announcements
r
Hi! Maybe someone here knows a better way to solve issue I have. I have to parse custom byte array into class. I want end class to be immutable. Currently this is my workflow
Copy code
private class InternalParamDefinition {
    var id = 0
    var type: Byte = 0
    var defaultValue: Any? = null
}

object ParamLoader {
    @JvmStatic
    fun load(id: Int, bytes: ByteArray): ParamDefinition {
        fun createInternal(): InternalParamDefinition {
            val param = InternalParamDefinition()
            param.id = id
            val buffer = PacketBuffer(bytes)

            while (true) {
                when (buffer.unsignedByte) {
                    0 -> return param
                    1 -> param.type = buffer.byte
                    2 -> param.defaultValue = <http://buffer.int|buffer.int>
                    3 -> param.defaultValue = buffer.string
                    else -> throw IllegalStateException("unknown field type")
                }
            }
        }

        val internalParam = createInternal()
        return ParamDefinition(
            id = internalParam.id,
            defaultValue = internalParam.defaultValue,
            type = internalParam.type
        )
    }
}
I have heard ideas about using Protobuf. Maybe there is some better way to do this?
e
If your only goal is immutability, you can use
fold
+ `copy`:
Copy code
data class ParamDefinition(
  val id = 0,
  val type: Byte = 0,
  val defaultValue: Any? = null
)
Copy code
return bytes.fold(ParamDefinition()) { param, byte ->
  when (byte /* unsigned logic missing */) {
    0 -> return@load param
    1 -> param.copy(type = buffer.byte)
    2 -> param.copy(defaultValue = <http://buffer.int|buffer.int>)
    3 -> param.copy(defaultValue = buffer.string)
    else -> error("unknown field type")
  }
}
r
Hmm this could work, tho now it is a lot of object creation
Thanks!
👍 1
e
Indeed, but object allocation on the JVM is very cheap (a pointer increment, basically), so if this code is not executed thousands of times, it won't problably be an issue