Paulo Cereda
10/21/2022, 5:25 PMvar , but I was wondering if there was a way of getting rid of them (just as a personal challenge). Of course, my life would be easier if BreakIterator could implement Iterable, but no luck. 😉 Here's the code added for convenience:
fun toGraphemes(str: String) = buildList {
val boundary = BreakIterator.getCharacterInstance()
boundary.setText(str)
var start = boundary.first()
var end = boundary.next()
while (end != BreakIterator.DONE) {
add(str.substring(start, end))
start = end
end = boundary.next()
}
}
Any suggestion is welcome! Thank you! 🦆Klitos Kyriacou
10/21/2022, 5:30 PMPaulo Cereda
10/21/2022, 5:42 PMIterable, it was more as a joke. 🙂 I will clarify in the original post, sorry!ephemient
10/21/2022, 5:46 PMfor loop if there is an operator fun iterator(): Iterator<?>, for example
operator fun BreakIterator.iterator(): Iterator<IntRange> = iterator {
var start = first()
while (true) {
val end = next()
if (end == BreakIterator.DONE) {
break
}
yield(start until end)
start = end
}
}
val text = "Hello, world!"
val breakIterator = BreakIterator.getWordInstance()
breakIterator.setText(text)
for (range in breakIterator) {
println(text.substring(range))
}
prints
Hello
,
world
!Paulo Cereda
10/21/2022, 5:48 PMephemient
10/21/2022, 5:53 PMoperator fun <T> Iterator<T>.iterator(): Iterator<T> = this
so while Iterator doesn't implement Iterable, you can write
for (i in iterator)