https://kotlinlang.org logo
#stdlib
Title
# stdlib
p

PHondogo

03/31/2023, 6:03 AM
Hello! Does stdlib contains multiplatform String.format(string, args) function?
e

ephemient

03/31/2023, 6:12 AM
c

CLOVIS

03/31/2023, 7:48 AM
Note that string interpolation works on all platforms.
p

PHondogo

03/31/2023, 7:50 AM
Yes. I need for runtime provided string with args.
c

CLOVIS

03/31/2023, 7:50 AM
Out of curiosity, what's the use case?
p

PHondogo

03/31/2023, 7:56 AM
In db there are string templates. And there is context info that flat mapped to array of values.
e

ephemient

03/31/2023, 10:20 PM
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

PHondogo

04/01/2023, 3:59 AM
Yes. I've done someting like this. Just wanted to be sure that I'm not doing things stdlib already have.
4 Views