Format in kotlin string templates

前端 未结 6 1334
青春惊慌失措
青春惊慌失措 2020-12-12 17:40

Kotlin has an excellent feature called string templates. I really love it.

 val i = 10 
 val s = \"i = $i\" // evaluates to \"i = 10\"

But

6条回答
  •  余生分开走
    2020-12-12 18:22

    Kotlin's String class has a format function now, which internally uses Java's String.format method:

    /**
     * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
     * using the default locale.
     */
    @kotlin.internal.InlineOnly
    public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
    

    Usage

    val pi = 3.14159265358979323
    val formatted = String.format("%.2f", pi) ;
    println(formatted)
    >>3.14
    

提交回复
热议问题