I know it's not much, but I find myself using this...
# stdlib
j
I know it's not much, but I find myself using this all the time:
fun <T> Iterable<T>.forEachBetween(item: (T)->Unit, between: ()->Unit)
which runs the
between
block between each call of
item
, but doesn't get called at the very beginning or end
e
For example? What kind of specific task you are using it for?
j
When I have to do something along the lines of
joinToString
, but I'm doing it with UI components. For example, placing dividers between components. Or for another example, when I'm writing something that emits large amounts of text using
Appendable
and want to directly use
append
instead of joining stuff to a string first.
I used it a bunch when I was making stuff to write out prepared SQL statements, as I would be adding values and text to the query at the same time.
e
Can you give the shortest example demonstrating a use of this
forEachBetween
function?
I’m trying to figure out what use-cases it achieves that are not covered by
joinToString
.
j
Copy code
//UI Example
fun _LinearLayout.addButtons() {
    val actions: List<Pair<String, () -> Unit>> = fromSomewhereElse()
    actions.forEachBetween(
        item = {
            button(text = it.first) {
                setOnClickListener { it.second() }
            }.lparams(matchParent, wrapContent)
        },
        between = {
            view { backgroundColor = Color.GRAY }.lparams(matchParent, 1)
        }
    )
}

//Query builder example
class SQLQuery(val stringBuilder: StringBuilder = StringBuilder(), val values: ArrayList<Any?> = ArrayList()): Appendable by stringBuilder {
    fun addValue(value: Any?){
        stringBuilder.append("\$" + values.size.toString())
        values.add(value)
    }
}
fun buildingQuery(){
    val columns = listOf("a" to 1, "b" to 2, "c" to 3)
    val query = SQLQuery()
    columns.forEachBetween(
        item = {
            query.append("SET ${it.first} = ")
            query.addValue(it.second)
        },
        between = {
            query.append(", ")
        }
    )
}