Hello! Does stdlib contains multiplatform String.f...
# stdlib
p
Hello! Does stdlib contains multiplatform String.format(string, args) function?
e
c
Note that string interpolation works on all platforms.
p
Yes. I need for runtime provided string with args.
c
Out of curiosity, what's the use case?
p
In db there are string templates. And there is context info that flat mapped to array of values.
e
you could build your own mini-formatter like
Copy code
fun String.format(vararg args: Any?): String = buildString {
    var index = 0
    var position = 0
    while (position < this@format.length) {
        val next = this@format.indexOf('%', startIndex = position)
        if (next < 0) break
        append(this@format.substring(position, next))
        when (val c = this@format.getOrNull(next + 1)) {
            '%' -> append('%')
            's' -> append(args[index++])
            'd' -> append((args[index++] as Number).toInt())
            'l' -> append((args[index++] as Number).toLong())
            'e', 'f', 'g' -> append((args[index++] as Number).toDouble())
            else -> throw IllegalArgumentException(if (c == null) "%" else "%$c")
        }
        position = next + 2
    }
    append(this@format.substring(position))
}
but supporting the full set of features that the Java string formatter has (which Kotlin/JVM simply delegates to) is challenging
🙏 1
p
Yes. I've done someting like this. Just wanted to be sure that I'm not doing things stdlib already have.