Here is some code which does not work. I suspect ...
# getting-started
a
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
?
Copy code
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)])
    }
}
This works but can it be made more elegant?
Copy code
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)])
        }
    }
}
a
Try
this@toHexString.forEach
❤️ 1
👀 1
a
Awesome! That works. Thank you @Adam Powell
👍 1
a
The same thing works any time you need to clarify a specific
this
in scope
👍 1
v
Or simply
Copy code
fun ByteArray.toHexString() = joinToString("") { it.toString(16).padStart(2, '0') }
🙂
❤️ 1