, 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:
Copy code
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! 🦆
k
Klitos Kyriacou
10/21/2022, 5:30 PM
Not an answer, but Iterator doesn't implement Iterable, so why should BreakIterator?
p
Paulo Cereda
10/21/2022, 5:42 PM
Sorry, I didn't mean it should actually implement
Iterable
, it was more as a joke. 🙂 I will clarify in the original post, sorry!
e
ephemient
10/21/2022, 5:46 PM
anything can be used in a
for
loop if there is an
operator fun iterator(): Iterator<?>
, for example
Copy code
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
Copy code
Hello
,
world
!
p
Paulo Cereda
10/21/2022, 5:48 PM
@ephemient This is brilliant, thank you so much! I've so much to learn!
e
ephemient
10/21/2022, 5:53 PM
this isn't meant to be an obscure feature of Kotlin either; kotlin-stdlib contains a
Copy code
operator fun <T> Iterator<T>.iterator(): Iterator<T> = this