Suppose you did a lot of "here's a ubytearray, i n...
# announcements
t
Suppose you did a lot of "here's a ubytearray, i need to pad it up to certain length with a value", what (if any) extension would you add? I'm not a fan of methods that take two integers, because you lose some safety due to the fact that it's easy to misguess the order of the parameters.
m
What about using named parameters?
j
But a ubytearray contains ubytes, not integers
t
fair that. i guess i was just frustrated that UByteArray.padded(value:UByte, size:Int) isn't anymore obvious/clear than UByteArray.padded(size:UInt, value:UByte). and casting about for a different sort of approach that I was missing
j
Add a JavaDoc and call it a day? 🙃
val padded = array + Array(size) { value }
t
val padded = original + Array(targetSize - original.size) { value }
j
Yeah, or along those lines you could write
original.padded(targetSize) { value }
which may or may not be enough of a distinction versus parenthetical declaration.
👍 2
t
I like that, thanks. it harmonizes nicely with the idiomatic constructor
d
How about matching the
Array
constructor? Writing the value in curly braces would definitely bring distinction.
Copy code
inline fun UByteArray.padded(size: UInt, init: (index: Int) -> UByte): UByteArray =
    this + Array(size - this.size) { init.invoke(this.size + it) }
Edit: Next time I will refresh messages pre posting.
👍 1
t
tangentially... why do you put the
inline
there? I see it in a lot of the core functions in the docs, but I never do it for any of mine. When should I think about doing that? And what do I get from it? I'm assuming it potentially makes things more optimal. In which case, wouldn't you only add it when you'd proved it was a pain point? Otherwise, why not just put inline everywhere?
j
You could call it paddedToLengthWith(length: Int, what: UByte) if you needed to, maybe.
d
I marked the function as
inline
to allow for inlining of the
init
lambda. The Kotlin documentation suggests inlining functions such as above to circumvent overhead related to higher-order functions - see https://kotlinlang.org/docs/reference/inline-functions.html Inlining ordinary functions may bring dimnishing (or negative?) returns on performance and bloat code size, but with very small higher-order convenience functions inlining can make sense.
🙏 1
j
If it does indeed match the array constructor you can use:
Copy code
inline fun UByteArray.padded(size: UInt, init: (index: Int) -> UByte) = this + Array(size - this.size, init)
Starting to feel more like a C macro 🤣
d
If you pass the
init
lambda directly,
init
's index parameter is not the index of the element in the resulting array, which may lead to confusion.
j
Ah, I see. yes.