Alec Muffett
10/25/2020, 3:48 PMthis
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)])
}
}
fun ByteArray.toHexString(): String {
val src = this
return buildString {
src.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)])
}
}
}
Adam Powell
10/25/2020, 4:01 PMthis@toHexString.forEach
Alec Muffett
10/25/2020, 4:03 PMAdam Powell
10/25/2020, 4:03 PMthis
in scopeVampire
10/25/2020, 4:19 PMfun ByteArray.toHexString() = joinToString("") { it.toString(16).padStart(2, '0') }
🙂