Format in kotlin string templates

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

    A couple of examples:

    infix fun Double.f(fmt: String) = "%$fmt".format(this)
    infix fun Double.f(fmt: Float) = "%${if (fmt < 1) fmt + 1 else fmt}f".format(this)
    
    val pi = 3.14159265358979323
    
    println("""pi = ${pi f ".2f"}""")
    println("pi = ${pi f .2f}")
    
    

提交回复
热议问题