Here is some code which does not work. I suspect that the reason that it does not work is that
this
in the
buildString
lambda does not refer back to the
ByteArray
, but instead to the implicit
StringBuilder
which is being built, and I suspect that the
forEach
is inheriting its iterator from the inner
this
, rather than the (shadowed) outer
this
.
HOWEVER: the code is cute, and I would like understand the problem to be certain, and to save the situation. Can I elegantly fix the shadowing problem in the existing code, rather than refactoring it to use a loop, or
with
or
apply
?
const val INT_TO_HEX = "0123456789ABCDEF"
fun ByteArray.toHexStringDoesNotWork() = buildString {
forEach {
val octet = it.toInt()
append(INT_TO_HEX[octet.and(MASK_UPPER_NIBBLE).ushr(4)])
append(INT_TO_HEX[octet.and(MASK_LOWER_NIBBLE)])
}
}