Format in kotlin string templates

前端 未结 6 1328
青春惊慌失措
青春惊慌失措 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:19

    Unfortunately, there's no built-in support for formatting in string templates yet, as a workaround, you can use something like:

    "pi = ${pi.format(2)}"
    

    the .format(n) function you'd need to define yourself as

    fun Double.format(digits: Int) = "%.${digits}f".format(this)
    

    There's clearly a piece of functionality here that is missing from Kotlin at the moment, we'll fix it.

提交回复
热议问题