We have CharSequence.repeat
which produces a String. I would like Char.repeat
which would also produce a String. Then you can do e.g. '*'.repeat(5)
and get a String.
Can this be added?
We have CharSequence.repeat
which produces a String. I would like Char.repeat
which would also produce a String. Then you can do e.g. '*'.repeat(5)
and get a String.
Can this be added?
What stops you from writing "*".repeat(5)
and getting the same result?
If you want something to add to stdlib, you have to give a use case for that. Especially when it could be don with one-liner extension.
Sometimes I’m working with Chars and not Strings. For example, this leetcode problem Loading...
Assuming we had Char.repeat
it would look like
fun customSortString(order: String, string: String): String {
val occurrences = string.groupingBy { it }.eachCountTo(HashMap())
return buildString(string.length) {
for (char in order) {
occurrences[char]?.also {
append(char.repeat(it))
occurrences -= char
}
}
for ((char, times) in occurrences) {
append(char.repeat(times))
}
}
}
This is a trivial example so even without Char.repeat
it’s fine:
fun customSortString(order: String, string: String): String {
val occurrences = string.groupingBy { it }.eachCountTo(HashMap())
return buildString(string.length) {
for (char in order) {
occurrences[char]?.also {
repeat(it) { append(char) }
occurrences -= char
}
}
for ((char, times) in occurrences) {
repeat(times) { append(char) }
}
}
}
The use case is the exact same as for CharSequence.repeat
except for when you’re dealing with Chars. A String is a sequence of chars so being able to repeat a char and get a String makes sense to me. I added a trivial example in another comment in this thread. And sure, I could, and have implemented it myself, but much like CharSequence.repeat
I think it’s a standard utility that others would find helpful.