Hi friends! <In this code>, I ended up using `var`...
# codereview
p
Hi friends! In this code, I ended up using
var
, 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
Not an answer, but Iterator doesn't implement Iterable, so why should BreakIterator?
p
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
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
@ephemient This is brilliant, thank you so much! I've so much to learn!
e
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
so while
Iterator
doesn't implement
Iterable
, you can write
Copy code
for (i in iterator)