I have multiple `Long` `Int` and `Byte` variables...
# android
l
I have multiple
Long
Int
and
Byte
variables which I use across my codebase but have to convert them to different types. Lets take a
Long
variable which I have to convert to int (
toInt()
) or byte (toByte()) at different places. Is it common to provide the same variable as
Int
or as Byte, e.g.
myVariableAsLong
,
myVariableAsInt
,
myVariableAsByte
? Does this approach make sense, is there another common approach for this case or is it pointless?
j
I don't think it's good practice to have duplicate variables. In bigger projects this could be harder to maintain. I would say just use the functions
j
I mean, how would that look in practice? About like this:
Copy code
object Consts {
  const val myVarAsInt = 23
  val myVarAsByte = myVarAsInt.toByte()
}
So you'd use it as
Copy code
foo(myVarAsByte)
instead of
Copy code
foo(myVar.asByte())
I'm not seeing the big advantage there, but if you do, nothing wrong with it. But having a single source of truth is definitely a good idea.
l
@Joshua Hansen @Juliane Lehmann Thanks for sharing your thoughts. Improving readability wasn't my intention but rather performance. But there is no performance penalty here I guess. I'm using okio library for byte operations, unfortunately most of the functions expect
Long
data type.
j
Ah, I see, hadn't thought about the possible performance penalty. My unsubstantiated guess here would be that any possible penalty from the conversion (provided that the compiler doesn't smartly precompile it anyway, but that I do not know) would be dwarfed by the actual operations - except when you massage single bytes in a tight inner loop.
l
true story. The operations do not happen in a loop so it's not a big deal. Thanks :)